0

Why does the following javascript log 3 3 times instead of 0, 1, and 2?

for (var i = 0; i < 3; i++) { 
  setTimeout(function() { 
    console.log(i); 
  }, 42); 
}

For each iteration, shouldn't a new function be created based on the value of i for that iteration? And then that function is passed as an argument to setTimeout?

Allan Chua
  • 9,305
  • 9
  • 41
  • 61
John Hoffman
  • 17,857
  • 20
  • 58
  • 81

1 Answers1

1

This is because the anonymous functions were referring to the variable i. By the time these anonymous functions are about to execute the value of i is 3 What would be a better solution is something like this:

for (var i = 0; i < 3; i++) { 
  setTimeout(function(i) { 
    console.log(i);
  }, 42, i);  
}

Caching the former values of the iteration index inside the scope of the anonymous functions would allow you to print 3 different values.

Allan Chua
  • 9,305
  • 9
  • 41
  • 61