This question has already been answered:
for (var i = 0; i < 10; i++) { setTimeout(function() { alert(i); }, 100); } This question has already been answered:
for (var i = 0; i < 10; i++) { setTimeout(function() { alert(i); }, 100); } 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 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); } i , or set the next setTimeout after the previous one has been completed. - RegentsetTimeout , 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 KrassSource: https://ru.stackoverflow.com/questions/545414/
All Articles