How to run a function after a time delay?

Hi,

I'm trying async rust with the async_std crate. I can't find a way to run a function after a specified delay.

Something like

task::spawn(async move {
    task::sleep(Duration::from_secs(1)).await;
    // run your function here
});

should work for 1 second delay for example. Imports are:

use std::time::Duration;
use async_std::task;

The code is untested, as I'm on mobile.

The "move" in async move is optional if the async block doesn't capture any variables (or would already move its captures anyways).

The answer above is assuming you meant the question as "run some code in the background after some time", not "wait some time, then run code", i. e. I'm assuming you want the function you're currently in to keep proceeding to run (or already return) possibly way before the specified delay has elapsed.

yes this should work. The behavior should be the same as with setTimeout(fn, duration) in js. Thank you.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.