How to sleep in NodeJS using async/await
The easiest way to sleep using async/await
in NodeJS is the sleep-promise package:
npm install --save sleep-promise
Using that package you can simply use await sleep(milliseconds)
syntax like this:
const sleep = require('sleep-promise');
// In any async function:
await sleep(2000); // Wait 2000 ms
Note that this sleep()
variant is fully asynchronous, IO and other asynchronous operations will still be able to continue in the background - sleep()
will not block the NodeJS process.
Full example:
const sleep = require('sleep-promise');
(async () => {
console.log("This prints immediately");
await sleep(2000);
console.log("This prints 2 seconds later");
})();