JavaScript

How to wait or sleep the code execution in JavaScript

Sleep is a function that is present in most programming languages and is used to delay the execution of code for a specified time. JavaScript does not have this function, so we use the setTimeout() function to perform the same task. Although it does not work exactly as we expect from the sleep function, we will use it to build our own custom sleep function in javaScript, in this article.

For example, if we need to log three messages to the console with a delay of one second, we can’t do it using the sleep function in JavaScript as it is not available. But we can work around this by using the setTimeout() function.

What is the setTimeout() method?

The setTimeout() method is used to set a timer to delay the execution of code. It executes the specified piece of code after the timer expires.

A lot of devs who have worked with the sleep() function find setTimeout() to be confusing. This is because they mistake the setTimeout() function to be a version of the sleep() function in JavaScript.

Unfortunately, the setTimeout() has its own rules and does not work the way the sleep() function does so JavaScript devs have to come up with ingenious solutions to make it work as a sleep() function.

In this guide, we will look at several such solutions and explain how we can use the setTimeout() function to pause the execution of JavaScript source code and wait between consecutive lines of code.

Unlike the sleep() function, if we just put a delay of one second using the setTimeout() method between the lines of JavaScript code, it does not work:

setTimeout(1000)
console.log("Showing after one second")
setTimeout(1000)
console.log("showing after another one second")

The code in the example above will execute without any delay as if the setTimeout() function doesn’t exist.

The problem with the code given above is that the setTimeout() method only delays the execution of the function that is passed to it as a callback function. However, we gave only one “delay” argument when it is actually supposed to get two different arguments. The first argument is supposed to be a callback function, and the second argument is supposed to be the “delay”. Now let’s try to do that and see what happens:

setTimeout(() => console.log("showing after one second"), 1000)
setTimeout(() => console.log("showing after another one second"), 1000)

This time the setTimeout() function will work but not as it is supposed to, as both the console log messages will be displayed at the same time instead of having a delay of 1000 milliseconds between them.

So why did setTimeout() fail?

The reason why setTimeout() fails in the example above is that the setTimeout() function itself works synchronously in JavaScript code but the call-back function inside the setTimeout() function creates a new entry in the asynchronous task queue which is executed after the specified time.

Since the specified time in both the setTimeout() function was the same and they were executed at the same time due to synchronous code execution if javascript (with a delay of just a few milliseconds), all the entries in the asynchronous task queue run simultaneously.

As you can see, setTimeout() is not an exact copy of the sleep() function, rather it just queues up code for later execution. So the question arises, how do we make it work like a sleep() function. We can do this by using increasing timeouts when calling the setTimeout() function:

setTimeout(() => console.log("showing after one second"), 1000)
setTimeout(() => console.log("showing after another one second"), 2000)

This works because the new entry in the queue is created at approximately the same time, but those entries have to wait for different amounts of time to be executed.

The method given above is the method that is used to delay the execution of some parts of code while the other parts run synchronously. However, if you want to halt the execution of the whole JavaScript code while asynchronously executing some other parts then you will need to create a custom sleep() function.

How to Write a Sleep Function

In JavaScript, we can create a custom sleep() function by using promises, async, and await. This works exactly as a sleep() function would in any other language.

However, this custom sleep() function needs to be used with the await keyword and should be called from within async functions.

var sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay))

var repeatMessage = async () => {
  await sleep(1000)
  console.log("showing after one second")
  await sleep(1000)
  console.log("showing after another one second")
}

repeatMessage();

Now, by using this custom build sleep method, you can halt the execution of the javaScript code for the desired amount of time.

Conclusion

JavaScript does not have the sleep() function by default to delay the execution of code but its asynchronous nature can be used to achieve the same task. The inbuilt setTimeout() method can be used to delay the execution of code but to truly make the code asynchronous in JavaScript and make it work like the sleep() function we need to use the promises, await, and async functions. In this article, we learned to create custom sleep() functions in JavaScript.

About the author

Shehroz Azam

A Javascript Developer & Linux enthusiast with 4 years of industrial experience and proven know-how to combine creative and usability viewpoints resulting in world-class web applications. I have experience working with Vue, React & Node.js & currently working on article writing and video creation.