It's because of closure, you should do something like that
for( var i=0; i< 10; i++) {
(function(j){
setTimeout(function(){ console.log(j); }, 10);
}(i));
}
This is basic javascript closure, you can read more here How do JavaScript closures work?
The problem is that the for loop finishes first, so at the end, i
will equal 10. After that, the setTimeout
functions will get called and when they check the value of i
, they'll find it equal to the last value from the for loop which 10.
What I did is called an IIFE (Immediately Invoked Function Expression)
which creates a new variable for the scope of the setTimeout
function, so when the timeout comes, it finds its own variable that hasn't changed.