JavaScript-setTimeout inside Loop not work correctly

Sovary May 8, 2022 650
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

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him