Crates.io | tokio-js-set-interval |
lib.rs | tokio-js-set-interval |
version | 1.3.0 |
source | src |
created_at | 2021-05-17 16:31:22.739333 |
updated_at | 2023-06-25 13:41:54.530165 |
description | Allows you to use `setInterval(callback, ms)` and `setTimeout(callback, ms)` as in Javascript inside a `tokio` runtime. The library provides the macros `set_interval!(callback, ms)` and `set_timeout!(callback, ms)`. |
homepage | https://github.com/phip1611/tokio-js-set-interval |
repository | https://github.com/phip1611/tokio-js-set-interval |
max_upload_size | |
id | 398654 |
size | 54,697 |
tokio-js-set-interval
The crate tokio-js-set-interval
allows you to use setInterval(callback, ms)
and
setTimeout(callback, ms)
as in Javascript inside a tokio
runtime (https://tokio.rs/).
The library provides the macros:
set_interval!(callback, ms)
,set_interval_async!(future, ms)
,set_timeout!(callback, ms)
,set_timeout_async!(async_callback, ms)
.Cargo.toml
[dependencies]
# don't forget that you also need "tokio" for the tokio runtime!
tokio-js-set-interval = "<latest-version>"
code.rs
use std::time::Duration;
use tokio_js_set_interval::{set_interval, set_timeout, clear_interval};
#[tokio::main]
async fn main() {
set_timeout!(println!("hello from timeout"), 25);
set_interval!(println!("hello from interval"), 10);
// you can clear intervals if you want
let id = set_interval!(println!("hello from interval"), 10);
clear_interval(id);
// give enough time before tokios runtime exits
tokio::time::sleep(Duration::from_millis(40)).await;
}
They behave similar to their Javascript counterparts, with a few exceptions:
tokio
runtime lives long enough.()
I'm not an expert in tokio
(or async/await/futures in Rust in general) and I don't
know if this follows best practises. But it helped me to understand how tokio
works.
I hope it may be helpful to some of you too.
The functionality behind is rather simple. However, it took me some time to figure out what kind of
input the macros should accept and how the generic arguments of the functions behind the macros
need to be structured. Especially the *_async!()
versions of the macros were quite complicated
during the development.
1.0
. Note that Rust >= 1.73
will deny tokio <1.18
.