0

for (var index = 1; index <= 3; index++) {
  setTimeout(function() {
    console.log('after ' + index + ' second(s):' + index);
  }, index * 1000);
}
 output:

 after 4 second(s):4
 after 4 second(s):4
 after 4 second(s):4
 after 4 second(s):4

I understand using "let" instead of "var" solves this problem, but my question is, how in the world does the callback function inside the setTimeout function knows to run 4 times given the execution of setTimeout starts after the loop is completed?

This is more of educated question and trying to better understand the problem with follow up questions. I can't figure out how the setTimeout function knows how many times to run the callback function.

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

Just add a console.log() outside setTimeout you will find the reason

for (var index = 1; index <= 3; index++) {
    // it will execute this line 3 times,then begin to invoke console.log inside setTimeout
    console.log("before: " + index) 
    setTimeout(function () {
       console.log('after ' + index + ' second(s):' + index);
    }, index * 1000);
 }
flyingfox
  • 13,414
  • 3
  • 24
  • 39