JavaScript
provides setTimeout() and setInterval() methods to delay execution of script. But, it doesn't provide any way to sleep execution at a single line. Let's build our custom sleep method.
TOC
- Prerequisites
- idea
- sleep API
- uses
- live interactive demo
Prerequisites
I am assuming that you know the above prerequisites.
Idea is to use a promise to wait for a number of milliseconds. We know, we can delay the execution of certain script using await
. Using await we can run the next script after the promise is resolved or rejected.
Let's build our sleep API
function sleep(ms){
return new Promise((resolve)=>{
setTimeout(()=>resolve(),ms);
})
}
The above sleep API will wait for some milliseconds, then it resolves the promise.
Uses
make sure to call this API inside the
async
function
async function test(){
// wait for 3 seconds
console.log("Waiting...");
await sleep(3000);
console.log("The wait is over");
}
Top comments (8)
I usually write it as
since there's no reason to introduce an additional closure.
You can also do that with value (that promise will resolve to) since
setTimeout
supports passing arguments..then(console.log)
I usually avoid to chaining in this case. Await would be great fit here.
Although great example
const sleep = ms => new Promise(res => setTimeout(res, ms))
Why would you go through all that work of creating a javascript promise when you can just use the
setTimeout
function and theclearInterval
function?To avoid "callback hell". Promises with
async
/await
allow you to write asynchronous code linearly, rather than nesting callbacks, which quickly becomes messy.If you might need to clear the timeout before it executes, the callback version is probably better though (you could build a clearable promise version, but it would be less easy to work with). Depends on your use case.
agree
Supposed in case, where you want to use
sleep
many times. If code goes long, say 1000 lines of code. In this case, it becomes hard to manage the code.Here we can just use,
code and sleep 🥱