arb
arb

Reputation: 7863

Stop Recursive Animation in jQuery

I have a recursive animation to make the text on the screen change color. I want some mechanism to stop this animation when the div looses visibility. In my actual site, this is on a dialog box. I want to stop all the animations when the dialog box closes. I tried using $.stop() but I don't think that can interrupt the call stack during a recursive call.

Here is the gist of what I'm doing:

javascript:

function rainbow() {
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $('#rainbow ul li').animate({
        color: hue
    }, 500, rainbow);
}
$(function() {
    rainbow();

    $("#stop").click(function() {

        $('#rainbow ul li').stop()

    });
});​

html

<div id="rainbow">
    <ul>
        <li>Apple</li>
        <li>Microsoft</li>
        <li>SUN</li>
    </ul>
</div>
<button id="stop" type="reset">Stop</button>

http://jsfiddle.net/cRar7/12/

Clicking the Stop button doesn't do anything, the animation continues.

Upvotes: 2

Views: 1199

Answers (3)

Sven Bieder
Sven Bieder

Reputation: 5681

If you set an interval instead of setting the animation self recursive it is no problem. Change your script to this:

function rainbow() {
    var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
    $('#rainbow ul li').animate({
        color: hue
    }, 500);
}
$(function() {
    var ani=setInterval(rainbow,500);

    $("#stop").click(function() {

        clearInterval(ani);

    });
});

Upvotes: 0

Yoshi
Yoshi

Reputation: 54649

Have a look at the first parameter to .stop

.stop( [clearQueue] [, jumpToEnd] )

clearQueue A Boolean indicating whether to remove queued animation as well. Defaults to false.

So:

$('#rainbow ul li').stop(true);

should work.

http://jsfiddle.net/cRar7/14/

Upvotes: 5

gion_13
gion_13

Reputation: 41533

well, you could use a flag to do the trick :

var shouldStop = false;
function rainbow() {
    if(shouldStop) return;
    // rest of animation code here
}

$("#stop").click(function() {
    shouldStop = true;
    $('#rainbow ul li').stop();
});

Here's the demo : http://jsfiddle.net/cRar7/13/

Upvotes: 1

Related Questions