Unlike other programming languages, JavaScript doesn’t have a built-in sleep method. So you cannot simply call a sleep() function to pause a Node.js program. However, there are other ways that you can make a program wait for a specified time.

This tutorial discusses three approaches: setTimeout, async/await, and the sleep-promise package.

Using setTimeout() to Wait for a Specific Time

The setTimeout() function schedules code for the runtime to execute once a set amount of time has passed. It accepts a function and a delay time in milliseconds. Here's the syntax:

        setTimeout(function(), timeInMs)

For example, say you had a function that prints on the console:

        function printSentence() {
    console.log("Using setTimeout()")
}

To run the above function after two seconds have elapsed, pass the function and the delay time of 2000ms to the setTimeout() function:

        setTimeout(printSentence, 2000)

While this works, it's not guaranteed your function will run exactly after two seconds. It will definitely take at least that amount of time, but it may take more.

Is setTimeout() Accurate?

Yes, but with some caveats. setTimeout() is an asynchronous JavaScript function which means it's non-blocking. The code you schedule is added to the event loop while the rest of your program continues.

After the delay time passes, your program will execute the scheduled code, but only when it is free to do so. If other code is in the call stack, it will execute first, even if the scheduled code is due to run. This is where extra delay time can occur, hence the inaccuracy.

Consider the following program.

        console.log("Hello World!")
 
function printSentence() {
    console.log("Using setTimeout()")
}
 
setTimeout(printSentence, 2000)
console.log("Done")

Here’s what the console will display when you run it:

        Hello World!
Done
Using setTimeout()

This program introduces a delay, but it only delays the code it passes to setTimeout(). The rest of the program continues, with the scheduled code only interrupting it once the duration has elapsed. If you want to run all this code in order, with a pause in the middle, using setTimeout() will not work.

One alternative is to write synchronous code that will block execution for as long as you need. For example, you could use a do...while loop to block the execution thread until the delay time is up:

        function delay(ms) {
    const date = Date.now();
    let currentDate = null;
 
    do {
        currentDate = Date.now();
    } while (currentDate - date < ms);
}
 
console.log("Hello World");
delay(2000);
console.log("Will be printed after 2 seconds!");

The delay() function loops until the current time is equal to, or greater than, its starting time plus the delay. The downside of this approach is that it’s CPU intensive, especially with large delays. The do...while loop has to calculate the time remaining after each millisecond.

Using Async/Await to Delay a Node.js Program

An await expression causes execution to pause until a Promise is resolved. It lets you run asynchronous code as if it were synchronous, but more efficiently than by manually blocking execution. You can only use await inside a function marked async.

        function delay(time) {
    return new Promise(resolve => setTimeout(resolve, time));
}
 
async function printSentence() {
    console.log("Hello World")
    await delay(2000);
    console.log("Will be printed after 2 seconds");
}
 
printSentence();

This is the output of the above program:

        Hello World
Will be printed after 2 seconds

Using the sleep-promise Package

The sleep-promise package simplifies the process of pausing Node.js programs. You only need to call it and specify the delay time in milliseconds.

Start by installing it via npm:

        npm install sleep-promise

Here’s an example of how you could use it in your program:

        const sleep = require('sleep-promise');
 
(async () => {
    console.log("Hello World.");
    await sleep(2000);
    console.log("Will be printed after two seconds.");
})();

When you run the program, the output will be as follows.

        Hello World.
Will be printed after two seconds.

Choosing a Suitable Approach

Implementing a sleep functionality in Node.js can be tricky. When deciding how to go about it, consider what you want to achieve. If you just want to delay some code, for a minimum amount of time, setTimeout() is a good option. But if you want to pause the execution of your entire program, you should use async/await.