I have been trying to understand the following piece of code for some time now:
for (var i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
});
}
I have an idea of why it produces the output:
5
5
5
5
5
But just wanted to clarify my understanding of how the event loop works in JavaScript.
Is it that each iteration creates an event in the event loop before the setTimeout runs?
I know that by default, the setTimeout function uses 0 as its milliseconds value, but that it only guarantees the minimum amount of time that the method will be added to the event queue.
Are the iterations added to the event queue before the setTimeout is?
[0] => [1] => [2] => [3] => [4] => [console.log]
Thanks