The following code uses a for-loop to add values to an array. Each time the current state of the array is logged in the console. Then a setTimeout function is used to create a delay of half a second between the outputs.
But the delayed output always shows the whole array with the status after it passed the whole for loop and not with the status when the setTimeout was invoked.
var my_array = [];
for (var i = 0; i < 10; i++){
my_array[i] = "Nr " + i;
console.log(my_array);
setTimeout(function(par) { console.log(par); }, 500*i, my_array);
}
How can that behavious be explained? Consider the follwing code, which is different because it sends the i-variable to the callback (instead of the array):
for (var i = 0; i < 10; i++){
console.log(i);
setTimeout(function(par) { console.log(par); }, 500*i, i);
}
This snippet logs the i-variable in a delayed output with its value of the time the setTimeout was invoked. As expected, it does not log the i-variable with the value it has after the for loop.