< 返回版块

WingDust 发表于 2021-12-22 17:59

Rust 怎么实现像 JavaScript settimeout 函数

评论区

写评论
作者 WingDust 2021-12-22 22:57

怎么有 settimeout 的 clearTimeout 功能

c5soft 2021-12-22 19:11

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"]}

c5soft 2021-12-22 18:57

可以使用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();
}

1 共 3 条评论, 1 页