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_sleep_promise.sh
npm install --save sleep-promise

Using that package you can simply use await sleep(milliseconds) syntax like this:

sleep_example.js
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:

sleep_full_example.js
const sleep = require('sleep-promise');

(async () => {
    console.log("This prints immediately");
    await sleep(2000);
    console.log("This prints 2 seconds later");
})();

 


Check out similar posts by category: Javascript, NodeJS