Future-based interval in the browser

Will this have the same effect as tokio::time::interval in the browser?

  • Approach 1 (using setInterval)
    • Let intervalId = setInterval(...)
    • The first tick should complete immediately (not relying on the interval)
    • On drop of the Interval, call clearInterval(intervalId)
  • Approach 2 (using setTimeout)
    • When ticking, store the result of the timeout in lastTimeoutId
    • Before polling a Rust future after a tick completes, assign lastTimeoutId to -1
    • The first tick should complete immediately (that is, setTimeout is not called)
    • On drop of the Interval, call clearTimeout(lastTimeoutId) if lastTimeoutId is not -1

The above Tokio docs has this example:

A simple example using interval to execute a task every two seconds.

The difference between interval and [sleep] is that an [Interval]
measures the time since the last tick, which means that [.tick().await]
may wait for a shorter time than the duration specified for the interval
if some time has passed between calls to [.tick().await].

If the tick in the example below was replaced with [sleep], the task
would only be executed once every three seconds, and not every two

use tokio::time;

async fn task_that_takes_a_second() {

async fn main() {
    let mut interval = time::interval(time::Duration::from_secs(2));
    for _i in 0..5 {

Which approach is closer to Tokio? And for setTimeout, do I need (Date.now() - lastTickInstant) + duration internally?

I recommend you watching this video when dealing with intervals on the browser.

1 Like

I'm thinking of using their solution in the video description, looks really easy!

You may find gloo-timers useful. It wraps the raw web-sys bindings of setTimeout and setInterval to provide callback-style and futures-style interfaces.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.