MattP
MattP

Reputation: 2863

JQuery / AJAX - Prevent Queue Build Up

Is there a way to stop a queue build up of JQuery AJAX calls?

I have a list of products and on Hover additional information is loaded via an AJAX call. The problem is if you run the mouse up and down the menu when you stop it creates a queue which you have to wait to catch up as it flicks through all the products.

I am using the Hide() function so when you come out of the menu it immediately reverts back to the default content but the queue is still going on in the background it's just hidden.

When you have a stack of elements with no margin is the mouseout part of the hover function called before the mouse in of the next element?

Current code is simply:

$("#product-menu a").hover(
                function() {
                    $("#product-welcome").hide();
                    $("#product-overview").show();
                    $("#product-overview").load("lib/product-overview.php", {"pid": this.id});
                },
                function() {
                    $("#product-overview").hide();
                    $("#product-welcome").show();
                }
            );

Upvotes: 2

Views: 1034

Answers (3)

Robert Beuligmann
Robert Beuligmann

Reputation: 1444

You can make something like your doing work using the .ajax() method you can store the jqXHR object and use it to call .abort() on a currently running ajax request. This wont work with .load because it does not give access to the jqXHR object.

It would look something like this,

var activeRequest;    
...
$("#product-menu a").hover(
                        function() {
                            ...
                            if(activeRequest.abort)
                            {
                                activeRequest.abort();
                            }
                            activeRequest = $("#product-overview").ajax(...);
                        },

Upvotes: 1

Josiah Ruddell
Josiah Ruddell

Reputation: 29831

Have a look at the $.ajaxPrefilter api.

$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {
    if(/*some condition*/)
       jqXHR.abort()
});

Upvotes: 0

inquam
inquam

Reputation: 12942

I would add a delay when you move your mouse over the product before it start's fetching information and also a locking variable that makes sure only one request is done at a time. Also, you should cache the data client side and not load() the same product overview over and over again if the user hovers over the product.

Upvotes: 0

Related Questions