AppDividend
Latest Code Tutorials

JavaScript Sleep: How to Make your Functions Sleep

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

JavaScript sleep

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

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

JavaScript does not have a built-in/native 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))
}

Arguments

We create a sleep() function that takes milliseconds as a parameter. The sleep() function will create 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 sleep() function in 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 be helpful to create a loop.

The task() function logs the Yello, D’oh value one by one 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 due to how JavaScript works (read more about the event loop), this does not pause the entire program execution as it might happen in other languages, but instead, only your function sleeps.

To demonstrate that it doesn’t pause, let’s add one simple line of code in the above code.

// 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 the task() function is complete, 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 on its way 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 the single-thread event-based model language. So while in the specific case, it might be nice to have the whole engine wait for a few seconds, in general, it is bad practice. But again, it depends on what you are trying to achieve and ensure the application’s performance.

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 the signal or callback to fire a given functionality; other devs will argue that sometimes an arbitrary moment of delay is useful.

But what I believe is that to each their own and 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 useful.

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

Your email address will not be published.

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