Jukke
Jukke

Reputation: 349

Using setTimeout to delay loop iteration

I would like to delay my while loop on each iteration. I tried the following:

var o = 1;
while(o<4){
    setTimeout("setupAnimation(o)",2000);
    //setupAnimation(o); //<--this works but everything happens att the same time
    o++;
}

I also tried to write it like this, which didn't work either:

var o = 1;
function repeatMe(){
    setupAnimation(o);
    o++;
    setTimout('repeatMe()',1000);
}

Any suggestions?

Upvotes: 2

Views: 558

Answers (5)

James Montagne
James Montagne

Reputation: 78630

Try this:

var o = 1;
function repeatMe(){
    setupAnimation(o);
    o++;
    setTimeout(function(){repeatMe();},1000);
}

repeatMe();

Upvotes: 2

Jacob Nelson
Jacob Nelson

Reputation: 2466

var o = 1;  //Global Variable
var animTimerId;  //Global Variable

function setupAnimation(o){
   // Your code goes here

   o++;
   if(o == 4){
     clearTimeout(animTimeoutId);
     break;
   }
}

function repeatMe(){
   animTimeoutId = setTimeout("setupAnimation(o)",2000);
}

Upvotes: 1

Wicked Coder
Wicked Coder

Reputation: 1118

if you want to use the second approach here's the working Javascript

<script type="text/javascript">

    var o = 1; 
    function repeatMe(){ 

    setupAnimation(o); 
    o++; 

    setTimout(repeatMe(),1000); 
    } 

    function setupAnimation(o){
        alert(o);
    }

    </script>

<a href='#' onclick="repeatMe()">Click Me</a>

Upvotes: 1

Digbyswift
Digbyswift

Reputation: 10400

You can use this:

setTimeout(function(){ myFunction(parameter)}, timeoutLength);

Upvotes: 0

Quentin
Quentin

Reputation: 943142

eval is slow, hard to debug and has potential security problems (depending on where the data comes from). Don't use it. (Passing a string to setTimeout uses eval by proxy.)

Pass a function to setTimeout instead. You'll need to use a closure to capture the current value of o for the function you pass.

You should probably also use a for loop here instead of a while loop. The syntax is clearer.

function setupAnimationFactory(o) {
    return function() {
        setupAnimation(o);
    }
}

for (var o = 0; o < 4; o++){
    setTimeout(setupAnimationFactory(o),2000);
}

Upvotes: 4

Related Questions