Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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);
 }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading