WingDust 发表于 2021-12-22 17:59
Rust 怎么实现像 JavaScript settimeout 函数
怎么有 settimeout 的 clearTimeout 功能
async/await版本:
use tokio::time::{sleep, Duration,Instant}; #[tokio::main] async fn main() { let me = "World"; println!("Current {:?}", Instant::now()); let now = Instant::now(); set_time_out( || { println!("Current {:?}", Instant::now()); println!("Hello {} ! --elapsed {:?}", me, now.elapsed()); }, Duration::from_secs(2), ).await; } async fn set_time_out(f: impl Fn() -> (), d: Duration) { sleep(d).await; f(); }
Cargo.toml
[dependencies] tokio={version="1.15.0",features = ["full"]}
可以使用sleep函数来延时,用闭包传入需要执行的代码:
use std::thread::sleep; use std::time::{Duration, Instant}; fn main() { let me = "World"; println!("Current {:?}", Instant::now()); let now = Instant::now(); set_time_out( || { println!("Current {:?}", Instant::now()); println!("Hello {} ! --elapsed {:?}", me, now.elapsed()); }, Duration::from_secs(2), ); } fn set_time_out(f: impl Fn() -> (), d: Duration) { sleep(d); f(); }
评论区
写评论怎么有 settimeout 的 clearTimeout 功能
async/await版本:
Cargo.toml
可以使用sleep函数来延时,用闭包传入需要执行的代码: