Consider following snippet?
for (var i = 0; i < 10; i++) { 
  setTimeout(function () { 
    console.log(i); 
  }, 0); 
}
What will be printed to the console?
Explanation
The function argument to setTimeout is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i, which is 10.

Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:

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

+леонид шишкин, Thanks! Fixed

2015 Aug 27, 11:25:02 AM

Answear is russian language.

2015 Aug 27, 10:41:44 AM

Слідкуй за CodeGalaxy

Мобільний додаток Beta

Get it on Google Play
Зворотній Зв’язок
Cosmo
Зареєструйся Зараз
або Підпишись на майбутні тести