This is an error known as Closure within a loop, the important thing to know is that it occurs when you create a function within the for cycle and you use the iterator function
There are several ways to solve it. In ECMAScript 2015, you can use let
in for
and it works without problems ( let
per var
)
for(let i = 0; i<3; i++){
alert("Primero->"+i);
setTimeout(function() {
alert("Segundo->"+i);
}, (i+1)*600);
}
Another option is to wrap the function created in an IIFE (self-executing function).
for(var i = 0; i<3; i++){
alert("Primero->"+i);
(function(i) {
setTimeout(function() {
alert("Segundo->"+i);
}, (i+1)*600)
})(i);
}
Finally, you can say the response of @ Error404, use a function declared outside the for
I need to use the index i in the alert.
I do not understand very well the execution of setTimeout, and because it waits to finish the for to begin the execution.
The problem arises from the nature of the variables var
of javascript (a characteristic, not a bug). These variables "live" in the lexical field of higher function. That is why it is solved with let
(which moves the variable to the scope of the local function, in this case the for) and with the other methods that create a new function that hides the varianble i
original.