Jump to content
Akinix
Sign in to follow this  
Perpetual Newbie

sleep() or delay() functions in JS

Recommended Posts

I spent some time finding this solution, so I decided to share it with you.

There is no sleep() or delay() functions in JS but you can easily implement it on your own using promises in combo with setTimeout():

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Usage:

await sleep(2000); // Sleep for 2 seconds

or

sleep(2000).then(() => {
    // Sleep for 2 seconds and then run the code from this block
});

 

Edited by Perpetual Newbie

Share this post


Link to post
Share on other sites
Sign in to follow this  

×
×
  • Create New...