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 the 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();

In this example, first, we have defined a sleep function. Then, we will call the sleep() function when we need to sleep the specific function.

In our code, that specific function is the task(). So, we will use the sleep() function in the task() function to sleep. 

Here, we used async-await because sleep() will return the promise. Before a function, the word “async” means one simple thing: a function always returns a promise. 2. The keyword “await” makes JavaScript wait until that promise settles and returns its result.

We defined an array list that can help create a loop.

The task() function logs the Yello and D’oh values within 1 second. So, for one second, the function goes to sleep, and after the promise is resolved, it will log the next time the same string, and then again goes to sleep for 1 second, and so on.

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));

Remember that this does not pause the entire program execution because of how JavaScript works (read more about the event loop), as it might happen in other languages. But instead, only your function sleeps.

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! 

Let’s run the above code and see the output.

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

You see the problem, and the Done is logged first, even if we have written in the last.

That is the way of handling the async code in JavaScript. This is because logging the statements here is an asynchronous operation in JavaScript.

When the JavaScript interpreter encounters the async function, it will not wait for the request to complete. Instead, it will continue and log the output “Done!” to the console, and when the request returns a couple of hundred milliseconds later, it will output the statements one by one.

The issue here is that JavaScript is a single-thread event-based model language. So while it might be nice to have the whole engine wait for a few seconds in this specific case, it is a terrible practice.

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

Why should you use JavaScript’s sleep function?

Sleep is a process control approach that tells your script to wait a specified number of 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.