0

I am confused by the output of the following code:

for (var i = 0; i < 5; i++) { 

    setTimeout(function() { 
        console.log(i); 
    }, i * 1000 );

}

The output is 5 5 5 5 5, there is a 1-sec delay between each 5.

I know var is function scoped, but the function inside setTimeout is also in the for loop. why the output isn't 0 1 2 3 4, there is a 1-sec delay between 0 and 1, a 2-sec delay between 1 and 2, a 3-sec delay between 2 and 3, a 4-sec delay between 3 and 4?

rhys_stubbs
  • 538
  • 6
  • 16
Kyle Zhang
  • 31
  • 5

0 Answers0