# How to delay or sleep a JavaScript function

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Oct 2, 2021, updated Sep 10, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-sleep-delay-wait-pause

> Learn how to use the setTimeout() method to delay a JavaScript function execution for a certain amount of time.

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](https://attacomsian.com/blog/java-pause-sleep-delay-wait) 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](https://attacomsian.com/blog/promises-javascript) in ES6,  we can easily implement such a feature in JavaScript to make a function sleep:

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

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

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

const sleep = promisify(setTimeout);
```

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

```javascript
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](https://attacomsian.com/blog/async-await-javascript) as shown below:

```javascript
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.
