-2

Say

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

I thought the above function would log as 0,1,2. But it logs out 2,2,2. Can anyone helps me to explain?

tnkh
  • 1,749
  • 2
  • 14
  • 30
  • Possible duplicate of [setTimeout in for-loop does not print consecutive values](https://stackoverflow.com/questions/5226285/settimeout-in-for-loop-does-not-print-consecutive-values) – JoshG Sep 13 '20 at 05:47

1 Answers1

0

The three iterations of your loop run all at once, and you're scheduling the callback of setTimeout() to occur in the future.

By the time they run, i already has the value of 2.

In other words, setTimeout() doesn't block the loop.

Brad
  • 159,648
  • 54
  • 349
  • 530