Wrap setTimeout
around an IIFE
var arr = [ 10, 12, 15, 21 ];
for(var i = 0; i < arr.length; i++) {
//console.log('outside timeout ' + i)
(function(i){
setTimeout(function(){
console.log('Index: ' + i + ', element: ' + arr[i])
}, 3000)
})(i);
}
Reasoning - var
are functional scope variables and even if specified in a if/for/while
will be available in the whole function. The condition governs the number of times the loop will run, which over here breaks when i becomes 4. However, when the timeout function is executed for the i=0
or i=1
and others, i has already reached 4 as it has completed the for loop. Hence, you need to explicitly pass the value of i using an IIFE.
Also, if you are using ES6 and above, you can use let
also specified by Satpal in comments.
var arr = [ 10, 12, 15, 21 ];
for(let i = 0; i < arr.length; i++) {
//console.log('outside timeout ' + i)
setTimeout(function(){
console.log('Index: ' + i + ', element: ' + arr[i])
}, 3000)
}