A sleep or delay function is a programming feature that allows you to pause the execution of a program or a specific part of a program for a specified amount of time. This can be useful in various situations, such as when you need to introduce a delay between two actions, create a time-based loop, or synchronize tasks in a multi-threaded application.
The sleep or delay function typically takes a parameter, which is the duration of the delay in seconds, milliseconds, or microseconds, depending on the programming language and library being used. Once the function is called, the program will “sleep” or “delay” for the specified amount of time before continuing its execution.
There are different ways to create a sleep or delay in Node.js, depending on whether you want to block the thread or not. Node.js is designed to be asynchronous and non-blocking, so blocking the thread is generally not recommended. However, there may be some cases where you need to do so, such as debugging or testing.
One way to create a non-blocking sleep is to use the setTimeout()
function, which takes a callback function and a time in milliseconds as arguments. The callback function will be executed after the specified time, but the rest of the code will continue to run.
You can use it to create a sleep function that returns a promise, and then use it with async/await syntax. For example:
// Define a sleep function that returns a promise
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
// Use the sleep function with async/await
async function main() {
console.log("Before sleep");
await sleep(1000); // Wait for one second
console.log("After sleep");
}
main();
This is a new API introduced in Node.js v15.0.0 that provides promise versions of the timer functions, such as setTimeout()
, setInterval()
, and setImmediate()
. You can import the setTimeout()
function from the timers/promises
module and use it with await syntax.
// Import the promise version of setTimeout
import { setTimeout } from "timers/promises";
// Use the setTimeout function with await
async function main() {
console.log("Before sleep");
await setTimeout(1000); // Wait for one second
console.log("After sleep");
}
main();
This sleep-promise package provides a simple sleep function that returns a promise. You can install it using npm or yarn, and then import it and use it with await syntax.
import sleep from "sleep-promise";
// Use the sleep function with await
async function main() {
console.log("Before sleep");
await sleep(1000); // Wait for one second
console.log("After sleep");
}
main();
If you really want to create a blocking sleep or delay in Node.js, you can use a while loop that checks the current time and waits until it reaches a certain value. However, this is not recommended as it will consume CPU resources and prevent other code from running.
const sleep = (millis) => {
var stop = new Date().getTime();
while (new Date().getTime() < stop + millis) {}
};
sleep(1000);
console.log("This printed after about one second");
console.log("This printed second");
Alternatively, you can use the execSync()
function from the child_process
module, which executes a command synchronously and blocks the process until it finishes. You can use this function to invoke your OS’s sleep command, which pauses execution for a specified number of seconds. However, this method is also not recommended as it depends on your OS and may have security risks.
const { execSync } = require("child_process");
execSync("sleep 1"); // block process for 1 second
console.log("This printed after about one second");
console.log("This printed second");