10

I have been using jQuery's stop(true, true) method to clear running animations so the next one starts immediately. I noticed that the first parameter, clearQueue, clears the entire animation queue but the second parameter, jumpToEnd, only jumps to the end of the currently running animation and not the ones that were removed from the queue. Is there a way to have it clear and jump to the end of all queued animations?

I've ended up chaining a few stop(false, true) calls instead, but this will only handle 3 queued animations, for example.

$(this)
  .stop(false, true)
  .stop(false, true)
  .stop(false, true)
  .addClass('hover', 200);

Edit:

I ended up adding my own method, stopAll, as per Ates Goral's answer:

$.fn.extend({ stopAll: function () {
    while (this.queue().length > 0)
      this.stop(false, true);
    return this;
  } });
$(this).stopAll().addClass('hover', 200);

I hope someone else finds this useful.

Jesse
  • 6,725
  • 5
  • 40
  • 45

4 Answers4

6

Chaining multiple stop(false, true) makes sense. Instead of hard-coding a fixed number of chained calls, you could check the queue length:

while ($(this).queue().length) {
    $(this).stop(false, true);
}

Demo: http://jsfiddle.net/AB33X/

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
4

jQuery 1.9 introduced the .finish() method, which achieves exactly that.

Vsevolod Golovanov
  • 4,068
  • 3
  • 31
  • 65
0

I also notice from the documentation of the .finish() method in jQuery 1.9 that

Animations may be stopped globally by setting the property $.fx.off 
to true. When this is done, all animation methods will immediately 
set elements to their final state when called, rather than displaying an effect.

There is also a nice demo of the various methods on the .finish() documentation page.

Andiih
  • 12,285
  • 10
  • 57
  • 88
0

Test for presence of class (set upon hover and removed on mouseOut animate callback) before staring new animation. When new animation does start, dequeue.

$("div").hover(function(){
    if (!$(this).hasClass('animated')) {
        $(this).dequeue().stop().animate({ width: "200px" });
    }
}, function() {
    $(this).addClass('animated').animate({ width: "100px" }, "normal", "linear", function() {
        $(this).removeClass('animated').dequeue();
    });
});
Said Erraoudy
  • 1,490
  • 1
  • 13
  • 21