JavaScript Sleep: How to Pause Code Execution

JavaScript does not have a built-in “sleep()” function that pauses the code execution for a specified period of time. But you can use methods such as setTimeout(), async/await, promises, or generators.

How to create a sleep function in JavaScript?

To create a sleep function in JavaScript, use the “combination of async/await with the setTimeout() function” or as a one-liner:

await new Promise(res => setTimeout(res, 1000));

There is another way to use Sleep in JavaScript. Use the combination of setTimeout() and Promise to delay your function execution intentionally.

Syntax

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

Parameters

We create a sleep() function that takes milliseconds as a parameter. The sleep() function will make a new Promise that will resolve in given milliseconds so that the execution will be paused until that. After resolving, it will start to continue the execution.

Example

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const list = [1, 2, 3, 4, 5]

const task = async () => {
  for (const item of list) {
    await sleep(1000);
    console.log('Yello, D\'oh');
  }
}

task();

Output

Yello, D'oh
Yello, D'oh
Yello, D'oh
Yello, D'oh

The above statements will be logged one by one after a 1-second delay.

If you don’t want to define the sleep() function, you can achieve this using a single line of code.

const list = [1, 2, 3, 4]

const task = async () => {
  for (const item of list) {
    await new Promise(r => setTimeout(r, 2000));
    console.log('Yello, D\'oh');
  }
}

task();

Here, we have just added the following line of code.

await new Promise(r => setTimeout(r, 2000));

Let’s add a short code to the above code to demonstrate that it doesn’t pause.

const sleep = (milliseconds) => {
  return new Promise(resolve => setTimeout(resolve, milliseconds))
}

const list = [1, 2, 3, 4]

const task = async () => {
  for (const item of list) {
    await new Promise(r => setTimeout(r, 2000));
    console.log('Yello, D\'oh');
  }
}

task();
console.log('Done!')

Here, we have added the last line, which logs the Done! After completing the task() function, the Javascript engine should print the Done! 

Output

Done!
Yello, D'oh
Yello, D'oh
Yello, D'oh
Yello, D'oh

But again, it depends on what you are trying to achieve and ensure the application’s performance.

Why should you use sleep in JavaScript?

Sleep is a process control approach that tells your script to wait milliseconds before continuing to the next line of code.

To improve the performance of your web applications, you should consider using the sleep() function on specific scenarios.

Using the sleep approach, one advantage is that you can reduce the number of HTTP requests and improve the performance of your code.

If user input or for APIs that have rate limits, it can be useful.

Caveats of Sleep in JavaScript

The infamous sleep, or delay, a method within any language, is constantly debated. Some developers will say that there should always be a signal or callback to fire a given functionality; other devs will argue that sometimes an arbitrary moment of delay is practical.

But I believe that to each their own; one rule can never decide anything in this industry. It is based on your needs and requirements.

The setTimeout() method does not hold up execution; it executes the next line of the method immediately after the timeout is SET, not after it expires. It does not achieve the same task that the sleep method would accomplish.

That’s it.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.