The example cited leaves me cold. It does not answer the question.
The intention of the code is to output numbers from 0 to 4 in the console every second. However, it outputs the number 5 five times.
The reason is that after five iterations, the value of the i variable is 5. And the five instances of the callback function passed to the setTimeOut() function refers to the same variable i with the final value 5.
Could someone explain this better? Why isn't the settimeout function called each time i changes? Why is the timeout function called 5 times with the same value for i?
for (var i = 0; i < 5; i++) {
setTimeout(function () {
console.log(i);
}, 1000);
}