How to suspend execution of a Node.js program

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

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

Using setTimeout() to wait for a specific time

the setTimeout() the function schedules the code for the runtime to run after a set amount of time has elapsed. It accepts a function and a delay time in milliseconds. Here is the syntax:

setTimeout(function(), timeInMs)

For example, suppose you have a function that prints to the console:

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

To execute the above function after two seconds have elapsed, change the function and delay time from 2000ms to the setTimeout() a function:

USE VIDEO OF THE DAY
setTimeout(printSentence, 2000)

While this works, it’s not guaranteed that your function will run exactly after two seconds. It will definitely take at least that long, but it may take longer.

Is setTimeout() accurate?

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

After the time has elapsed, 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 run first, even if the scheduled code should run. This is where additional delay 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")

This is what the console will show 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, the programmed code not interrupting it until the time has elapsed. If you want to run all this code in order, with a break in the middle, using setTimeout() will not work.

An alternative is to write synchronous code that will block execution for as long as necessary. For example, you can use a to do while loop to block the thread of execution until the delay time elapses:

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() the function loops until the current time is equal to or greater than its start time plus the delay. The downside of this approach is that it is CPU-intensive, especially with large delays. The do…while loop must calculate the remaining time after each millisecond.

Using Async/Await to delay a Node.js program

A wait The expression suspends execution until a promise is resolved. It allows you to execute asynchronous code as if it were synchronous, but more efficiently than manually blocking execution. You can only use await inside a marked function asynchronous.

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();

Here is the output of the above program:

Hello World
Will be printed after 2 seconds

Using the Sleep Promise Package

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

Start by installing it via npm:

npm install sleep-promise

Here is an example of how you might 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.

Choose an appropriate approach

Implementing sleep functionality in Node.js can be tricky. When deciding how to go about it, think about what you want to accomplish. If you just want to delay some code, for a minimum of time, setTimeout() is a good option. But if you want to interrupt the execution of your whole program, you have to use asynchronous/wait.


PC screen with code blocks in a code editor

Synchronous and asynchronous programming: how are they different?

Read more


About the Author

Comments are closed.