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.

Make your mark

Join the writer's program

Are you a developer and love writing and sharing your knowledge with the world? Join our guest writing program and get paid for writing amazing technical guides. We'll get them to the right readers that will appreciate them.

Write for us
Writer of the month
Marin Bezhanov
Marin is a software engineer and architect with a broad range of experience working...
Build on top of Better Stack

Write a script, app or project on top of Better Stack and share it with the world. Make a public repository and share it with us at our email.

community@betterstack.com

or submit a pull request and help us build better products for everyone.

See the full list of amazing projects on github