Ever wondered how you can do each iteration of a for loop with some delay? That means, the code block in for loop body will be executed until the condition goes wrong, but with a delay in each iteration.

Suppose, I want to display an alert in each 5s, for 10 times.

Yeah there are timers in JavaScript, like setInterval and setTimeout. SetInterval is a time interval based code execution method that has the native ability to repeatedly run a specified script when the interval is reached. setTimeout is a time based code execution method that will execute a script only one time when the interval is reached.

What will happen if I put a setTimeout in a for loop to alert something with a delay?

function timeoutFunction()
{
  alert("hi");
  for(i = 0; i < 10; i++) {
    setTimeout(function () {
      alert("hello");
    }, 3000);
  }
}
timeoutFunction();

Run it in codepen

After first alert, there is a 3s delay, but the alert inside for loop is executed without delay.

What’s the reason?

The setTimeout() function is non-blocking and will return immediately. Therefore your loop will iterate very quickly and it will initiate 3s timeout triggers one after the other in quick succession. That is why first alerts pops up after 3s, and all the rest follow in succession without any delay.

What can solve this problem?

Immediate Invoking Function Expression(IIFE) can be used to get what we want. It will look like this by syntax.

(function () {

})();

IIFE immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.

The same function using IIFE will give us the desired output.

alert("hi");
for (var i = 0; i < 5; i++) {
  (function (i) {
    setTimeout(function () {
      alert("hello");
    }, 3000*i);
  })(i);
};

Run it in codepen

As an application of this, I created a Codepen, which can be found here: Run it in codepen.

First function is called when body is loaded, and it calls the second function on the last iteration of its for loop. Like that, other function calls the first function, on its last iteration. And it continues.

References: