Search code examples
javascriptjavascript-objectsecmascript-2016

How does the setTimeout() in javascript knows how many times to loop inside of a for loop?


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.


Solution

  • 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);
     }