for (var i = 0; i < 10; i++) { setTimeout(function() { alert(i); }, 100); } 

Reported as a duplicate by members user194374, aleksandr barakin , cheops , Denis , Grundy Jul 17 '16 at 15:42 .

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 .

  • because the author of the example wrote this way. would like 20 - would write 20 :) - PashaPash
  • I do not understand, the question? - Mr. Black
  • I suspect that the author expects to see 1, 2, 3, 4 .. but you need to read how the anonymous function works. - xEdelweiss

1 answer 1

Because by the time of operation of setTimeout , the cycle is already fully executed and the variable will take a value of ten. And once at the time of the call, the variable is already equal to ten, then ten will go to the output.

An easy example of what is happening:

 a = 10; setTimeout(function() { console.log(a); }, 1000); a += 20; //выполнится раньше, чем вывод 

To solve this, you need to remove the dependency and create a local closure. Since in JS the scope of functions, you need to create a function and pass it the value at the current time. Then it will be copied and not used as a link.

  for(var i = 0; i < 10; i++){ (function(i) { setTimeout(function(){ console.log(i); }, 100); })(i); } 

  • Also, by the way, it can be mentioned that in order for the delay to be equal between the entire iterations, you must either make the delay time dependent on i , or set the next setTimeout after the previous one has been completed. - Regent
  • @Regent, is there any simple way to make the sequential execution of several setTimeout , so that it would work like in a global area, so being executed inside a function? I just can’t guess how to do it without global variables. - Alex Krass
  • one
    Something I did not understand the phrase "worked like a global area, so being performed inside a function . " Perhaps you are talking about this option ? - Regent
  • @Regent, yes, I'm talking about this option, thanks. - Alex Krass