Unexpected execution of setTimeout Javascript

3

For the following instruction:

for(var i = 0; i<3; i++){  
     alert("Primero->"+i);

     setTimeout(function() {
        alert("Segundo->"+i);
      }, (i+1)*600);

}

The output is as follows:

  

First-> 0

     

First - > 1

     

First-> 2

     

Second-> 3

     

Second-> 3

     

Second-> 3

I need to use the i index 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.

    
asked by nachfren 23.10.2016 в 12:54
source

2 answers

2

You would need to pass a callback function to your setTimeout function. Something similar to this:

for(var i = 0; i<3; i++){
     alert("Primero->" + i);
     setTimeout(muestraValores, (i+1)*600, i);
}

function muestraValores(i){
  alert("Segundo->" + i);
}

The parameters should be passed as the third argument so that the setTimeout respects the delay when executing the function.

    
answered by 23.10.2016 / 13:03
source
4

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.

    
answered by 23.10.2016 в 14:05