AppDividend
Latest Code Tutorials

JavaScript Sleep: How to Make your functions sleep

0

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

JavaScript sleep

To make your functions sleep in JavaScript, use the combination of setTimeout() and Promise to delay your function execution in your intentional way.

Syntax

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

In this example, we are creating a sleep() function that takes milliseconds as a parameter.

The sleep function will create a new Promise that will resolve in given milliseconds, so until that, the execution will be paused. 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. We will call the sleep() function when we need to sleep the specific function.

Now, 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. The word “async” before a function 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 the gap of 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, then you can achieve this using the 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 one 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 demonstrates 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!. That means, 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. Rather, it will continue on its way, and log the output “Done!” to the console, and when the request returns the 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. 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 totally depends on what you are trying to achieve and make sure about the performance of the application.

Caveats of sleep in JavaScript

The infamous sleep, or delay, a method within any language is always 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 totally 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 the timeout expires, so that 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 cause may developers a headache. That is how you deal with them completely depends upon what you’re trying to achieve.

That is it for the JavaScript sleep function example.

Leave A Reply

Your email address will not be published.

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