var count = 0; for ( var i = 0; i < 4; i++ ) { setTimeout( function(){ assert( i == count++, "Check the value of i." ); }, i * 200); } 

Please explain how this code works. Why does the loop run four times with a value of 4?

Reported as a duplicate at Grundy. javascript 5 Sep '17 at 6:39 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • @setback, I never heard about the function assert in JS. What does she do, explain ... - Rules
  • I understand that the cycle starts first, runs to the value of four, then setTimeout starts. But why? Maybe someone will throw a link which one to read ..? - setback
  • one
    @Rules, nothing to do with the function. Author, you need to use closures. - lampa
  • one
    @lampa: it just uses the closures of the vehicle (according to the variable i ), doesn't it? He needs to use them correctly . - VladD
  • one
    @VladD says everything correctly, the variable i is in closure with respect to the function that is passed to setTimeout - Specter

2 answers 2

Problem with handlers in loop

  • Close as a repeat? +1 - VladD
  • controversial issue, on the one hand, the topic is similar - the cycle and asynchronous functions, on the other - it is not so obvious - Specter


The setTimeOut itself works asynchronously, that is, the assert i function runs out 4 times for a global variable and when the assert function is executed, it is already 4 times. The cycle runs faster.

a clear demonstration of this fact first cycle passed then worked assert s