Node.js Sleep
In JavaScript to sleep a function for a certain amount of time we have sleep function. It is helpful to pause the execution of a function for any decided amount of time. Regardless of the language sleep function can be used. JavaScript doesn’t have a native sleep function. After the introduction of promises async/await we can implement sleep in a readable way.
Install sleep in Node.js using npm.
npm install --save sleep-promise
It is easy to use a sleep function. Using this npm package use async/await.
const sleep = require('sleep-promise');
// In any async function:
await sleep(2000); // Wait 2000 ms
sleep variant is fully asynchronous so it will not block any other process.
const sleep = require('sleep-promise');
(async () => {
console.log("This prints immediately");
await sleep(2000);
console.log("This prints 2 seconds later");
})();
Comments
0 comments
Please Sign in or Create an account to Post Comments