Javascript, Event loop, setTimeout, IIFE, closure
Based on references below, my understanding of the following code is:
setTimeout() is non-blocking and handled by the Browser Web APIs, which put the callbacks on the callback queue when the timer is done. Then the event loop waits for the call stack to be free to run each callback in turn. setTimeout closure closes over the anonymous IIFE and has the correct value of index for each iteration.
for(var i = 0; i < 3; i++){
(function(index){
setTimeout(function(){
console.log(index);
}, 5000);
})(i);
console.log("loop="+i);
}
/*Output in console is
loop=0
loop=1
loop=2
//after 5 seconds
0
1
2
*/
I'm looking for an explanation of what's happening with the following code in Chrome.
for (var i = 0; i < 3; i++) {
setTimeout(
function(index) {
console.log(index);
}(i), 5000
);
console.log("loop="+i);
}
/* Output in console without any delay is:
0
loop=0
1
loop=1
2
loop=2
*/
Why is 'console.log(index)' executed immediately, without a 5 second delay?
How does the web API execute setTimeout() with a callback as an IIFE?
Are any callbacks put in the callback queue?
Does the event loop move any callbacks to the call stack?
Or is setTimeout() being ignored and its callback being executed immediately on the call stack?
References I've consulted:
Philip Roberts: What the heck is the event loop anyway? | JSConf EU 2014 https://www.youtube.com/watch?v=8aGhZQkoFbQ
Philip Roberts Help I'm stuck in an event loop 2016 https://www.youtube.com/watch?v=6MXRNXXgP_0
Call Stack & Event Loop https://www.youtube.com/watch?v=mk0lu9MKBto