0

Consider the following code:

for (var i = 1; i <= 5; i++) {
    setTimeout(function printNumbers() {
        console.log(i);
    }, i * 1000);
}

I know that it is not a good practice to define functions inside a loop but it is not the main problem. I was expecting this code to print 1,2,3,4,5 a second apart from each other but it print 6 five times a second apart. My two questions are:

Why it is not printing the desired result? How does the counter even reach 6 when my condition is to stop at 5

Soviut
  • 88,194
  • 49
  • 192
  • 260
achref
  • 1,150
  • 1
  • 12
  • 28
  • 1
    *"How does the counter even reach 6 when my condition is to stop at 5"* Your condition is to stop at 6: `i<=5`. If `i` is `5`, the loop is executed one more time. – Felix Kling May 25 '16 at 18:28
  • Yes but it is not supposed to print the 6 right? – achref May 25 '16 at 18:29
  • 4
    `setTimeout()` being asynchronous allows the loop to run through `i++` to the end before `console.log(i)` is ever invoked. By that time, `i === 6`. The function is only able to remember `i`, not that `i` used to equal `3`, for example. – Jonathan Lonowski May 25 '16 at 18:29
  • This is a nice overview about JS' event loop: https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop – Felix Kling May 25 '16 at 18:30
  • 2
    @achref: All of the functions you are passing to `setTimeout()` are *sharing* the same `i` value. Those functions don't get ran until after the loop is done, and `i` has been set to 6. Check the [2nd duplicate question](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) listed for more info about why they all have `i` being 6 and how to fix it. – gen_Eric May 25 '16 at 18:30
  • Ok I see, so how do I get it to print the result I want, I mean 1,2,3,4,5 a second apart? – achref May 25 '16 at 18:32
  • @achref The answers for the linked question (with "*simple practical example*") explain 3 options that you can use – a closure, an iterator function, and `let`. – Jonathan Lonowski May 25 '16 at 18:36
  • @Jonathan yes I am reading it right now, thank you! – achref May 25 '16 at 18:38

0 Answers0