2

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?

5 Answers 5

4

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Unless I'm misunderstanding this, this is just going to delay the entire thing by 2 seconds rather than spacing out each call. Equivalent to just setting timeout once for the entire thing. I took the question to mean he wanted to space out the iterations.
2

Try this:

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

repeatMe();

Comments

1

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>

Comments

1
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);
}

Comments

0

You can use this:

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

2 Comments

That won't work, since o is in a loop and will change to the last value before any of the timeouts hit 0.
Yes, good spot. However, you could declare a variable in the scope of the anonymous function to transfer o as the parameter, I think.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.