Window.setTimeout is not reading the correct values

This is the code

var _d=1000;
for(var ii=0; ii<4; ii+=1){
    console.log(_d*ii);
    window.setTimeout(applyState(ii,_d),_d*ii);
} 

      

I want the applyState () function to be called 4 times with 1 second delay in between. What really happens is that everyone is called at once.

+3


source to share


2 answers


Operator

()

calls a function, you must pass that function, otherwise the return value of the function is passed to the function setTimeout

. But this will not completely solve the problem. The block for

does not create a new area. You can use the self-start function:



var _d=1000;
for(var ii=0; ii<4; ii+=1){
    (function(a) {
         console.log(_d * a);
         window.setTimeout(function() {
            applyState(a,_d);
          },_d*a);    
    })(ii);
} 

      

+3


source


you need to pass the setTimeout function, you are currently passing the return value to applyState (ii, _d)

try

window.setTimeout(function(){applyState(ii, _d);}, _d*ii)

      



if applyState doesn't actually need any arguments, in which case you can simply use

window.setTimeout(applyState, _d*ii)

      

0


source







All Articles