chandra hasa
Sep 5, 2018 · 1 min read

I have two answers to this problem..

Solution 1: Change var to let

for (let i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log(‘Index: ‘ + i + ‘, element: ‘ + arr[i]);
}, 3000);
}

Solution 2: Passing the index and value to the self invoking function

for (var i = 0; i < arr.length; i++) {
(function(i, val) {
console.log(‘Index: ‘ + i + ‘, element: ‘ + arr[i]);
}(i, arr[i]))
}