The issue is that by the time the inner function gets executed, the value of i
is 10, that's why you're getting 10, 10 times.
Closures 'close' over variables not over values. This means that the closure (the function inside the setTimeout
) has access to the variable at the time it executes no to the value of the variable when the closure was created.
So effectively you are executing the following code:
var i;
for(i=0; i<10; i++ ){
}
// delay 0ms
console.log(i);
// some delay
console.log(i);
// some delay
....
Also remember that JS is a single threaded language, so the first setTimeout
can't execute until you "yield", that means that the first function inside the setTimeout
only executes when the for loop finishes, it doesn't matter how small a delay you specify in the setTimeout