I have been looking at the anwers already posted on StackOverflow and none of them are satisfactory. They all give a practical solution to the problem, which doesn't solve my issue.
So take a look at this example:
for(var i = 1; i <= 5; i++) {
setTimeout(function(){
console.log(i)
}, 1000);
}
This is the classic example, which always yields:
6
6
6
6
6
This is all fine and dandy. The way I understand this is that the for loop runs and sets 5 timeouts to run after 1 second. When 1 second has passed the function inside the setTimeout will run. Since this is 1 second, i will long before that have gotten the value 6.
So I tried something else. What if I set the timeout to equal 0ms? Will that change the outcome?
for(var i = 1; i <= 5; i++) {
setTimeout(function(){
console.log(i)
}, 0);
}
No it doesn't.
6
6
6
6
6
This makes no sense. Why would the asyncronous setTimeout function run only after the for loop is done. I even tried setting the for loop value i <= 50000 and still the same outcome. This makes no sense whatsoever. In my head, once 1ms has passed, the setTimeout calls the function regardless if it's inside the for loop or not. Can someone please explain this to me? Thanks, i've read countless medium, stackoverflow and blog articles, but it still doesn't click. The scope explanation also doesn't help.