Watch Out When Using SetTimeout() in For Loop #JS
var array = [1, 2, 3, 4, 5]for(var i = 0; i < array.length; i++) {
setTimeout(() => {
console.log(array[i])
}, 1000);
}
When you see the above code snippet, what do you expect the console.log(array[i]) will print? 1, 2, 3, 4, 5 respectively? If you think so, that’s wrong! The answer is undefined * 5. Why would it log undefined, 5 times?

Why?
The reason being is that for loop only exits until the set condition breaks. For the above for loop, it will exit once i = 5. Therefore, i equals 5 when the for loop exits.
var array = [1, 2, 3, 4, 5]for(var i = 0; i < array.length; i++) {
setTimeout(() => {
console.log(array[i])
}, 1000);
}
// i = 5
setTimeout function in JavaScript usually takes a callback function as an argument. A callback function is a function that is executed after another function finishes running. In this case, it will run after for loop finishes. At this point, i is already 5 when the console.log([i]) is about to be executed. Due to the closure of JavaScript, the console.log has access to the i =5 which is defined as an outer layer of the setTimeout. Thus, when the console.log is executed, it logs undefined(array[5] = undefined) five times.
Solution
- Factor out the setTimeout function and invoke it immediately in the for loop.
var array = [1, 2, 3, 4, 5]for(var i = 0; i < array.length; i++) {
delay(i)
}function delay(i) {
setTimeout(() => {
console.log(array[i])
}, 1000);
}
2. Declare the variable i in the for loop with let instead of var. The let keyword from ES6 creates a separate scope for the code block that allows for loop to print the consecutive variables.
var array = [1, 2, 3, 4, 5]for(let i = 0; i < array.length; i++) {
setTimeout(() => {
console.log(array[i])
}, 1000);
}
