I'm studying closures but I don't understand why the second is always 1 instead of 2, 3, 4, 5 respectively. What I understand is here that since each function (even iife) has its own scope. Each i
variable is captured its own stack actually that's why it allows changes of values of i
though had been var
used.
In the same way, setTimeout
should catch each different i
variables having 1,2,3,4,5 (seconds) respectively. But, it doesn't seem such as seen in the image. Could you help?
- Maybe it is helpful that
i
is not a free variable forsetTimeout
. (no idea it is of any relation)
Code
for (let i = 1; i <= 5; i++) {
(function (i) {
setTimeout(function () {
console.log(i)
}, i * 1000)
})(i)
}