0

I am doing animation in jquery. I have a looping picture moving from left to right of the webpage. I used following code:

 function run() {  $("#run").animate({ left: "980px" }, 250).animate({
  left: "-600px" }, 0);   setTimeout("run()", 250);
 }

I want to stop the loop(OR break the function) once I press a button.

2
  • "stop the loop" as in "stop the animation directly"? If so, you can look into .stop as well (in addition to clearing the interval). Commented Mar 14, 2012 at 15:57
  • setTimeout can take a function as a parameter: setTimeout(run, 250) Commented Mar 14, 2012 at 16:01

4 Answers 4

3

setTimeout returns a vlaue that can be used to cancel it,

//Start
var ref = setTimeout(...);
//Stop
clearTimeout(ref);

Also, if just using a function, it is safer to just pass that than forcing an eval,

setTimeout(run, 250);
Sign up to request clarification or add additional context in comments.

Comments

0

It sounds like you want this animation to run until the user presses a button. For that I would set up a setInterval loop and use clearInterval to stop it on the button click

var runTimer = setInterval(function() {
  $("#run").animate({ left: "980px" }, 250).animate({ left: "-600px" }, 0);   
}, 250);

$('#stopAnimation').click(function () {
  clearInterval(runTimer);
}

2 Comments

"setInternal" should be "setInterval" for all you copy-pasters :P
@jbabey thanks, I can't tell you how many times i've made that spelling mistake :(
0

You want to call clear timeout.

var timeout;

 function run() {  $("#run").animate({ left: "980px" }, 250).animate({
  left: "-600px" }, 0); 
   timeout =setTimeout("run()", 250);
 }
 function cancel() { clearTimeout(timeout); }

Comments

0

try the method stop() before each animation

function run() { 
    $("#run").stop().animate({ left: "980px" }, 250, function(){
        $(this).css('left', '-600px');
    });
    setTimeout("run()", 250); 
}

1 Comment

setTimeout can take a function as a parameter: setTimeout(run, 250)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.