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, an interval 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.
The interval is not stoppable (unless the application stops). Strictly speaking, there should be a way to clear an interval, similar to javascript. But because this library is mainly for educational reasons and for “low priority indefinetely running background tasks”, this is not implemented yet. If you need it, create an issue or a PR.
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; }