Sometimes, we want to create a sleep or delay in Node.js that is not blocking with JavaScript.
In this article, we’ll look at how to create a sleep or delay in Node.js that is not blocking with JavaScript.
How to create a sleep or delay in Node.js that is not blocking with JavaScript?
To create a sleep or delay in Node.js that is not blocking with JavaScript, we can use a promise.
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 that calls setTimeout
which calls resolve
after millis
milliseconds.
Then we call sleep
in test
with 1000 to pause for 1000 milliseconds.
Conclusion
To create a sleep or delay in Node.js that is not blocking with JavaScript, we can use a promise.