How to Sleep in node.js?

Better Stack Team
Updated on April 4, 2024

In Node.js, there is no built-in sleep function like in some other programming languages. However, you can use the setTimeout function to simulate a sleep-like behavior. Here's a simple example:

 
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

async function example() {
  console.log('Start');

  // Sleep for 3 seconds
  await sleep(3000);

  console.log('End');
}

example();

In this example:

  1. The sleep function returns a Promise that resolves after a specified number of milliseconds.
  2. The example function is an asynchronous function that uses await to pause execution for the specified duration.
  3. The example function sleeps for 3 seconds (3000 milliseconds) between the "Start" and "End" log statements.

This approach is non-blocking and works well with the asynchronous nature of Node.js. If you need a synchronous sleep in a specific context, you may need to reconsider your design to leverage asynchronous patterns, as synchronous sleep can block the event loop and negatively impact the performance of your application.

Got an article suggestion? Let us know
Explore more
Licensed under CC-BY-NC-SA

This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.