Macro tokio_js_set_interval::set_interval[][src]

macro_rules! set_interval {
    ($cb:ident, $ms:literal) => { ... };
    (|| $cb:expr, $ms:literal) => { ... };
    (move || $cb:expr, $ms:literal) => { ... };
    ($cb:expr, $ms:literal) => { ... };
    ($cb:block, $ms:literal) => { ... };
}
Expand description

Creates a timeout that behaves similar to setInterval(callback, ms) in Javascript for the tokio runtime. Unlike in Javascript, it will only be executed, if after the specified time passed, the tokio runtime still lives, i.e. didn’t got dropped.

As in Javascript, a timeout may only have side effects and no return type. You don’t get a handle to manually wait for it, you must ensure, that the tokio runtime lives long enough.

Parameters

  • #1 expression, closure-expression, block or identifier (which points to a closure). The code that represents the callback function.
  • #2 time delay in milliseconds

Example

use tokio::time::Duration;
use tokio_js_set_interval::set_interval;

#[tokio::main]
async fn main() {
    set_interval!(println!("hello1"), 50);
    println!("hello2");
    // prevent that tokios runtime gets dropped too early
    // "hello1" should get printed 2 times (50*2 == 100 < 120)
    tokio::time::sleep(Duration::from_millis(120)).await;
}