1

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

User 5842
  • 2,849
  • 7
  • 33
  • 51
  • 1
    Take a look at this video https://www.youtube.com/watch?v=Nzokr6Boeaw – rafaelcastrocouto Aug 19 '18 at 21:40
  • Related: [What's the difference between using "let" and "var" to declare a variable in JavaScript?](https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var-to-declare-a-variable-in-jav) – klutt Aug 19 '18 at 21:51
  • The event queue is not really important here. You could store the functions, call them directly after the loop, and get the same result. See dupe link. – ASDFGerte Aug 19 '18 at 22:08

1 Answers1

1

Each message in the event queue corresponds to a function. Functions added to queue by your setTimeout will be only triggered after your main function completes.

As example:

    for (var i = 0; i < 5; i++) {
        setTimeout(function() {
            console.log(i);
        });
    }
    console.log('test')

it will output:

test
5
5
5
5
5
guijob
  • 4,413
  • 3
  • 20
  • 39