If I understand your question correctly, you want to print 0...4. You can achieve that by using let
instead of var
which creates a new binding of i
for each loop iteration [1], [2]:
// Prints 0, 1, 2, 3, 4:
for (let i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
Your suggestion to add an argument i
to the callback fails as the calling function setTimeout
doesn't pass anything to the callback. Thus the i
argument is undefined.
Alternatively, use the classic IIFE approach:
for (var i = 0; i < 5; i++) {
(function(i) {
setTimeout(function() {
console.log(i);
}, 1000);
})(i);
}
Even better, of course, would be to move the for-loop into the setTimeout
callback. But I assume you chose this code for demonstration purposes only.