What is the logic behind the IIFE function and the logic behind setTimeout()
in a loop.
There are two for
:
for (var i = 0; i < 10; i++) {
// Standard
setTimeout(function() {
console.log("Standard" + i);
}, 1000 * i);
}
for (var j = 0; j < 10; j++) {
// IIFE
(function(j) {
setTimeout(function() {
console.log("IIFE " + j);
}, 1000 * j);
})(j);
}
Now when I run with node.js, I have this result after 10 seconds (each console.log()
is executed every second):
Can someone explain to me the runtime logical difference between the invocation of the first function and the second ?
Especially if you can answer these questions:
- Why the log is executed each second in both
for
? (1000 * i|j is ignored) - Why the value of
i
always 10?
Thank you in advance.
[Edit]
I don't understand why in both for
the console.log()
is fired every second but the timeout seconds 1000 * i|j
may be a visible timeout.