JavaScript-setTimeout inside Loop not work correctly

Sovary May 8, 2022 381
1 minute read

setTimeout() is a awesome function in JavaScript which can execute at specific duration, but you should be aware of when use inside the loop (for, for-each, while) :

Basic syntax setTimeout:

setTimeout(function()
{
  //your logic to be execute in 1s
  console.log("hello");
}, 1000);

Problem

The above code should print hello after a second. It can ruin into problem if we use with loop. The variables you're passing in don't keep their initial values, so if you're changing them (as in a for loop) please be aware:

for (var i = 1; i < 5; i++) 
{
  setTimeout(function()
  {
    console.log(i);
  }, 1000);
}

We expect that gonna print out 1,2,3,4 within each delay 1 second. Acutally, this will output the value 5 four times, which is not the intention.

Solution

To handle this we can separate the timeout function into another funciton as below:

for (var i = 1; i < 5; i++) 
{
  setDelay(i);
}

function setDelay(i) 
{
  setTimeout(function()
  {
    console.log(i);
  }, 1000);
}


We can deal with this by declare the variable i in the for loop with let instead of var. The let keyword from ES6 creates a separate scope for the code block that allows for loop to print the consecutive variables

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


That's it we can do with that, but it seems abit take long line of code or we can use ES6 style with arrow function and let keyword.

Javascript 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him