for (j=1;j<=5;j ++) { (function(i){ setTimeout(function(){console.log(i)}, j*500) })(j) } 

This particular code is specifically interested in why the delay does not increase by 500 ms? I would be grateful if someone described the principle of the function.

  • 3
    why so Very much increased. If you do not believe, then replace j * 500 with just 500, and you will see that all five messages in the console will be displayed at the same time, and not at set intervals - DreamChild
  • 3
    I think that the author of the question expects that messages will be displayed after 500, 1500, 3000, 5000, 7500 ms, and he leaves 500, 1000, 1500, 2000, 2500 ms. - KoVadim 5:43 pm
  • one
    Hmm, in my log: 21: 24: 46.268 time 21: 24: 46.834 time 21: 24: 47.334 time 21: 24: 47.836 time 21: 24: 48.331 time In general for such cases it is convenient to use console.timeStamp (), console .time (label), console.timeEnd (label). In general, you should not rely on the ideal accuracy of browser timers, sometimes they behave incorrectly. Errors can be observed in this case, but "in general" everything works. - y0uix

1 answer 1

You essentially run five functions at the same time, i.e. Your code is identical:

 (function(i){setTimeout(function(){console.log(i)}, 1*500)})(1) (function(i){setTimeout(function(){console.log(i)}, 2*500)})(2) (function(i){setTimeout(function(){console.log(i)}, 3*500)})(3) (function(i){setTimeout(function(){console.log(i)}, 4*500)})(4) (function(i){setTimeout(function(){console.log(i)}, 5*500)})(5) 

That leads to the effect of displaying five messages in the console with an interval of 500 milliseconds.

  • I do not know why, but my values ​​are displayed with a periodicity of 0.5 seconds - pzb
  • one
    it should be. - KoVadim
  • one
    You, apparently, expect that each next function call occurs only after the completion of the previous one. This is not true. You, in fact, simultaneously start 5 timers: 500 500 500 500 500 Time: 0 ... 500 ... 1000 ... 1500 ... 2000 ... 2500 | ----> console.log (500) ; | ----------> console.log (1000); | ----------------> console.log (1500); | ------------------------> console.log (2000); | ------------------------------> console.log (2500); - Chad