I was going through an example explaining the use of var
in a loop where there is a setTimeout
:
for (var i = 0; i < 10; i++) {
setTimeout(function() { console.log(i); }, 100 * i);
}
logs out
10
10
10
10
10
10
10
10
10
10
The explanation is that the loop executes completely and then the setTimeout
.
In the following example, setTimeout
block is wrapped in an immediately-invoked function:
for (var i = 0; i < 10; i++) {
(function(i) {
setTimeout(function() { console.log(i); }, 100 * i);
})(i);
}
which shows
0
1
2
3
4
5
6
7
8
9
Is this because of both:
An IIFE executing immediately means that even if it contained a
setTimeout
, thesetTimeout
would be executed immediately. I.e. An IIFE trumps any asynchronous code inside it and executes it immediately?The function scoping of the IIFE shadows
i
but creates a separate variable that tracks the value of the outeri
at each iteration
EDIT (An additional question that I didn't articulate well in the original post):
Why does asynchronous code (setTimeout
) execute after the loop is completed whereas in the second example it executes immediately at each iteration?
Thanks