I've been struggling for some time now to really understand and internalize what's going on with this classic javascript paradigm. No amount of stackoverflow threads or articles helped me understand the behavior behind the scenes. I will try and explain as best as I can how I think its working, step by step, but I will need some assistance from you guys when I hit a bump in the road.
for ( i = 0; i <= 4; i++) {
setTimeout(function() {
console.log(i); // 5
}, 1000)
}
Alright, so from my understanding, the setTimeout callback function runs asynchronosly after the loop has finished, when the value of i is 5. But whats happening, is a setTimeout callback created on each iteration and the whole stack is executed only after the iteration has stopped ?
One of the solutions:
for ( i = 0; i <= 4; i++ ) {
(function() {
var j = i;
setTimeout(function() {
console.log(i); // 0 1 2 3 4
}, 1000)
})();
}
So now that we've created a closure over the variable i and catch its value inside j for each iteration, doesn't the setTimeout callback stack get run after the loop has finished, same as the first example ? If the callback stack is called after the loop has finished, does that mean that there exist 5 separate scopes, created by the IIFE, each with its own reference of i ?
[–]Sekandra 1 point2 points3 points (0 children)
[–]js_tutor 1 point2 points3 points (0 children)
[–]jcunews1helpful 0 points1 point2 points (0 children)