jQuery - Pausing and resuming a looping animation too quickly causes the queue to go haywire
<p>I have the following code that animates forever, pauses at the end of the current animation on mouse enter, and resumes on mouse leave. It works how I want it to except for one issue.</p>

<p>If I hover in and out of the element too quickly (e.g. by cutting across the corner) it causes some kind of queue build up and everything goes haywire. However when I actually check the queue there's nothing strange in it and the animations are obviously not even running in the queued order.</p>

<p>Using the following code waggle your mouse in and out of the grey area. When you eventually allow the animations to resume they will go haywire (also available at <a href="http://jsfiddle.net/54YTx/" rel="nofollow">http://jsfiddle.net/54YTx/</a>).</p>

<pre><code>$('body').html('&lt;div style="background: lightgrey;"&gt;Testing&lt;/div&gt;');

function do_animations() {
    // Always 0 or 1
    console.log($('div').queue('fx').length);

    $('div')
        .delay(1000)
        // Hardcoded numbers mean that resuming from the bottom position takes longer but it doesn't matter in this simple example
        .animate({'padding-top': '100px'}, 1000)
        .animate({'padding-top': '0px'}, 1000)
        // Queue instead of callback so that clearQueue() can stop the loop reliably
        .queue(function() {
            do_animations();
            $('div').dequeue();
        });
};
do_animations();

$('div').hover(function() {
    // Don't use stop(). We want the current animation to finish
    $('div').clearQueue();
}, function() {
    do_animations();
});​
</code></pre>
