0

So I was reading You Don't Know Javascript: Closures and Scope Chapter 5 and I came upon this code:

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

}

I failed to understand why does this print '6' 5 times. According to me: i=0 -> we come upon setTimeout and console.log(i) should print 0, wait for 1 second, and then one iteration of the for loop is completed. The next time the loop runs, i will = 2 and so on and so forth.

Help will be appreciated :)

  • Because all five callbacks close over the same `i` variable, and they run after the loop is complete. (`setTimeout` just schedules a callback, it *doesn't* make the code calling it wait until that timeout expires.) So they see the value `i` has *then*, after the loop. See the linked question's answers for details. – T.J. Crowder Oct 06 '18 at 14:59
  • Are you forgetting that `setTimeout` is aynchronous? It doesn't "print 0, then wait for 1 second", it sets up a timer that prints 0 a second later. And the code doesn't just wait for a second, it continues running and doing other stuff during that second. (This is what "aynchronous" means.) – Robin Zigmond Oct 06 '18 at 15:00

0 Answers0