Use Iife In Settimeout In A Loop, But Why?
I know it is a classic js question: (My question is not how to solve this problem, but how IIFE solve this problem. Thanks for the other answer link but I didn't find the answer I
Solution 1:
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.
Post a Comment for "Use Iife In Settimeout In A Loop, But Why?"