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.