jQuery: How to prevent queue build ...

How to prevent animation queue build up

I am sure you have come across some sort of animated navigation that is powered by jQuery while surfing around the web. And sometimes you will find that when you move your mouse over the buttons back and forth, and then move away, the animation can take a few seconds to stop. This is what’s called ‘animation queue build up’ and can become quite fustrating when first using the animate() method. But thankfully this can easily be prevented by adding a simple jQuery method called stop()

So let’s take a quick look at an example of animation queue build up, by running the mouse cursor back and forth or up and down over the menu below:

The code that we used for this is as follows:


  $(document).ready(function() {
        var out = 20;
        var backIn = 0;

	$('#tut_menu li').hover(function() {

	$(this).animate({ left: out}, 'fast');	

	}, function() {

	$(this).animate({ left: backIn}, 'fast');

	});
});

Now lets see how we can prevent the animation build up. All we do is add the .stop() method before we call animate.


  $(document).ready(function() {
        var out = 20;
        var backIn = 0;

	$('#tut_menu li').hover(function() {

	$(this).stop().animate({ left: out }, 'fast');	

	}, function() {

	$(this).stop().animate({ left: backIn }, 'fast');

	});
});

Here is the navigation menu again, but using the above code.

As you can see, the animation is no longer queued up by moving your mouse up and down over the menu items and this will certainly save you a lot of frustration ( which i found out) when the time comes to use this technique.

One Response to “jQuery: How to prevent queue build up”

  1. Jan:

    Nice article thanks for the tip!

Leave a Reply