How to delay or sleep a JavaScript function

Many programming languages provide a sleep() function that pauses the execution of the code for a certain amount of time. For example, in Java, you can use the Thread.sleep(2 * 1000) to halt the current thread execution for 2 seconds.

Similarly, PHP has sleep(2), and Python has time.sleep(2) to make the program stops for 2 seconds.

However, this functionality is not available in JavaScript due to its asynchronous execution model. But after the introduction of promises in ES6, we can easily implement such a feature in JavaScript to make a function sleep:

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

If you are using Node.js, just use the promisify utility:

const { promisify } = require('util');

const sleep = promisify(setTimeout);

Now you can use the above sleep() function with the then callback:

console.log(`Start time --> ${new Date().toISOString()}`);

sleep(2 * 1000)
  .then(() => console.log(`After 2s --> ${new Date().toISOString()}`))
  .then(() => sleep(2 * 1000))
  .then(() => console.log(`After 4s --> ${new Date().toISOString()}`));

// Start time --> 2021-10-02T08:35:31.993Z
// After 2s --> 2021-10-02T08:35:34.002Z
// After 4s --> 2021-10-02T08:35:36.004Z

For better readability, you can replace the then() callbacks with async/await as shown below:

const timer = async () => {
  console.log(`Start time --> ${new Date().toISOString()}`);

  // Wait 2 seconds
  await sleep(2 * 1000);
  console.log(`After 2s --> ${new Date().toISOString()}`);

  // Wait 2 more seconds
  await sleep(2 * 1000);
  console.log(`After 4s --> ${new Date().toISOString()}`);
};

timer();

// Start time --> 2021-10-02T08:42:34.754Z
// After 2s --> 2021-10-02T08:42:36.763Z
// After 4s --> 2021-10-02T08:42:38.764Z

Remember that due to the asynchronous nature of JavaScript, it is not possible to stop the entire program execution. Therefore, the above sleep() method will only suspend the execution of the function where you'll call it.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.