JavaScript

How to delay/wait in Javascript code execution?

Functions that can delay or halt the execution of a chunk of code are very crucial in a programming language as they are a way of controlling the flow of the program. There are many built-in “delay” or “wait” functions available in most programming languages. But in JavaScript, there is no delay, wait, or sleep function because it is a scripting language and scripting languages are always synchronous and single-threaded.

Initially, it may not seem a big deal, but as you progress in the world of programming you will realize the importance of “delay” and “wait” functions. So, if there is no wait \ delay \ sleep function then there is no way of controlling the execution of a program in JavaScript? Well, there are different functions and methods that help us achieve the same task in JavaScript.

Using setTimeout() function

The first and the most common method in implementing a delay in the execution of a JavaScript code is to use the setTimeOut() method. You’ll do a very common mistake of assuming the syntax is:

setTimeout( delay in ms );

Whereas in reality, this method takes a callback function. Keeping that in mind we can look at the syntax as:

Syntax of setTimeout() function

setTimeout( function , delay in ms);

To better understand the working of the setTimeout() method, let’s try and solve a problem.

Example
Suppose that we want to print numbers from 1 to 10, with a delay of 1 second in between each number.

The traditional way would be:

for (let i = 1; i <=10 ; i++ ){
setTimeout(1000);
console.log( i );
}

The output of the code is instantly printing all 10 digits like:

Because we are not passing anything to the setTimeout() method.

To add the delay using the setTimeout() method we think that the correct way is :

for (let i = 1 ; i  console.log(i), 1000 );
}

Rather than getting a 1-second delay after every number, what we get is a 1-second delay in the start and then all the numbers are printed instantly. As shown below:

We had the initial delay, but no delay after that. Why is that so? Well, the way the setTimeout() works is that it always runs in synchronous mode. This means that even having multiple calls to the same function will result in the delay of 1 sec.

What we did was, we invoked each setTimeout() method one after another and due to the asynchronous nature of the setTimeout() method, it does not wait for the previous setTimeout() method to finish and then execute the next one.

So ultimately we made 10 calls to setTimeout() method all having the same delay time. There is a way to fix this, and that is by using increasing delay timer like:

setTimeout( () => console.log(i), 1000 );
setTimeout( () => console.log(i), 2000 );
setTimeout( () => console.log(i), 3000 );

The above code example of printing 10 numbers would become this:

for (let i = 1 ; i  console.log(i), i * 1000 );
}

We are using the increasing value of the “i” variable and multiplying it with the 1-second delay to create incrementing delays for each call of setTimeout()

The output with this becomes:

We finally did it. But there is still something wrong here. That is the fact that calculating delays this way is very complicated especially when you are working in a real-world application. There is a way for that too, create your own delay/wait method.

How to Code your own delay/wait function?

We want a better solution, what we can do is code our own “delay” method. We will be using the setTimeout() function and promise to help us create the “delay” method as:

We will simply create a function with the name of “delay” and pass it time in milliseconds. This “delay” function returns a promise and won’t let the execution go on until the promise is resolved.

function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

Now, we call this “delay” function with a “.then ” operator. Like this:

console.log("Hello");
delay(2000).then(() => { console.log("World!"); });

The Output would be:

We are creating a promise and setTimeout() method with some delay to resolve the promise. You can read more about JavaScript Promises.

In case you want to get rid of the .then() method, and to chain the delays, what we can do is to use async and await with our “delay” function.

async function demo() {
  console.log("This is a");
  await delay(1000);
  console.log("LinuxHint");
  await delay(1000);
  console.log("Tutorial!");
}

Note: we need to add the async keyword with the function that calls the delay() method. If we run the program what we get is this:

Coming to our problem, the number printer from 1 to 10, we need to create it inside an async function and call the “delay” method which we just created like:

async function numberPrinter() {
  for (let i = 1; i <= 10; i++){
      console.log(i);
      await delay(1000)
  }
}

And we need to call this function with:

numberPrinter();

The output that we get with this is:

That is it for our “delay” function.

Conclusion

There is no built-in wait, delay, or sleep function in JavaScript, but we can use the setTimeout() method to mimic the delay behavior and we can even code our own delay() method to create a delay in the execution of the program. We have learned how setTimeout() method works, how it is common to misunderstand its working and usage. Moreover, we learned how to combine the setTimeout() method with promises to create our own delay method, and we also learned how to use async and await on our function to wait and then continue the execution.

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.