Sometimes, we want to create a sleep or delay in Node.js.
In this article, we’ll look at how to create a sleep or delay in Node.js.
How to create a sleep or delay in Node.js?
To create a sleep or delay in Node.js, we can create a function that returns a promise to pause execution for a specific amount of time.
For instance, we write
const sleep = (millis) => {
return new Promise(resolve => setTimeout(resolve, millis));
}
const test = async () => {
await sleep(1000)
console.log("one second has elapsed")
}
to define the sleep
function that returns a promise which calls setTimeout
with resolve
as a callback after millis
milliseconds.
Then we call sleep
in test
with 1000 to pause the function for 1000 milliseconds and then call console.log
to log "one second has elapsed"
.
Conclusion
To create a sleep or delay in Node.js, we can create a function that returns a promise to pause execution for a specific amount of time.