Question: 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.

Answer: 
Have a look at the first parameter to [.stop](http://api.jquery.com/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/>
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/>