JavaScript Sleep: How to Pause Code Execution

0
2132
JavaScript Sleep - How to Create functions sleep

Is there a better way to create sleep in JavaScript? Yes, since the release of ES2015-2022, there has been lots of improvement in JavaScript, and now you can engineer the sleep the way you want.

JavaScript sleep

JavaScript sleep is a technique that allows you to pause the execution of a script for a given period. It’s useful for situations where you want to wait for a particular event to occur or to ensure that a script doesn’t run too often.

Why should you use JavaScript’s sleep function?

Sleep is a process control approach that tells your script to wait for a specified number of milliseconds before continuing to the next line of code. It is a great way to improve the performance of your web applications.

By using the sleep method in JavaScript, you can reduce the number of HTTP requests and improve the performance of your code.

It can be helpful when waiting for user input or for APIs that have rate limits. If you’ve ever written a JavaScript program that had to wait for something before it could continue, you can use a “sleep” function.

How to write a sleep function in JavaScript?

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

JavaScript does not have a built-in sleep() function, but thanks to the introduction of promises (and async/await in ES2018), we can implement such features in a transparent and precise way to make your functions sleep.

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

// app.js

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.

// app.js

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.

// app.js

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.

// app.js

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! 

Now, 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.

What is the best way to cause JavaScript to sleep?

The best way to make JavaScript sleep is to combine async-await and promise. It will work as you would expect it should.

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.

Conclusion

JavaScript sleep is a debatable concept. Due to the nature of single-threaded language, we can’t achieve the complete sleep functionalities as other languages did. But sometimes, in some cases, the above solution is practical.

Timing issues in JavaScript may cause developers a headache. However, dealing with them entirely depends upon what you’re trying to achieve.

That is it for this tutorial.

Leave A Reply

Please enter your comment!
Please enter your name here

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