HTMLBOY Javier Usobiaga, web designer & front-end developer.

Using .stop() or .clearQueue() to avoid animation queues in jQuery

This is a common problem when animating with jQuery: let’s say you code a navigation with a soft animation on mouse hover, or an extra element appears when you hover a trigger element. If we hover several times in a row, every new animation won’t start until the previous one ends, creating a “queue” that will make the animation repeat several times (which usually is an unwanted effect).

This effect can be avoided using the .stop() method in our script:

$(".trigger-element").hover( function () { $(this).stop().animate({width:"100px"},500); }, function () { $(this).stop().animate({width:"80px"},500); } );

When .stop() is called on the element, the currently-running animation will be stopped, so the next one will start immediately instead of queueing. Unfortunately the .stop() method only works with animations, so if we want to avoid any other kind of function queue we should use .clearQueue() instead.

You can see a demo with both cases and you can get more information about .stop() and more information about .clearQueue().