For the following statement:
for(var i = 0; i<3; i++){
alert("Primero->"+i);
setTimeout(function() {
alert("Segundo->"+i);
}, (i+1)*600);
}
The output is the following:
First->0
First->1
First->2
Second->3
Second->3
Second->3
I need to use the index i in the alert.
I don't understand very well the execution of setTimeout, and why it waits for the for to finish to start the execution.
This is an error known as Closure inside a loop, the important thing to know is that it occurs when you create a function inside the for loop and use the iterator in the function
There are several ways to solve it. In ECMAScript 2015, you can use
let
infor
and it works without problems (let
byvar
)Another option is to wrap the created function in an IIFE (self executable function).
Finally, you can, as @Error404's answer says, use a function declared outside of the for
The problem arises from the nature of javascript variables
var
(a feature, not a bug). These variables "live" in the lexical scope of the parent function. That is why it is solved withlet
(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 thei
original variable.You would need to pass a function as a callback to your
setTimeout
. Something similar to this:You should pass the parameters to it as the third argument so that it
setTimeout
respects the delay when executing the function.