There is a useful plugin that Corey Frang posted on stackoverflow for queueing ajax requests. In my case, it’s useful for loading up large collections of data in “chunks” so as to minimise user perceived slowness. It works perfectly, except when a pagination event is triggered before the queue of ajax requests has completed, in this case, the container holding the loaded objects will clear, but the queued requests will continue to run, resulting in undesired behaviour. What I would like is to find / learn of a way to clear the queue of all existing requests. The developer posted a way to do this, however, it doesn’t appear to work. I’ve tried reading up on .queue on the jQuery site, but I can’t seem to understand how to make this work. I have already spent a lot of time trying to figure out this problem, but perhaps my lack of familiarity with some of the more complex aspects of jQuery is holding me back. Hope that someone out there who is more familiar with jQuery can help 🙂 ( marked what was suggested and does not appear to work with some “!!!!!” )
/*
* jQuery.ajaxQueue - A queue for ajax requests
*
* (c) 2011 Corey Frang
* Dual licensed under the MIT and GPL licenses.
*
* Requires jQuery 1.5+
*/
(function($) {
// jQuery on an empty object, we are going to use this as our Queue
var ajaxQueue = $({});
$.ajaxQueue = function( ajaxOpts ) {
var jqXHR,
dfd = $.Deferred(),
promise = dfd.promise();
// queue our ajax request
ajaxQueue.queue( doRequest );
// add the abort method
promise.abort = function( statusText ) {
// proxy abort to the jqXHR if it is active
if ( jqXHR ) {
return jqXHR.abort( statusText );
}
// if there wasn't already a jqXHR we need to remove from queue
var queue = ajaxQueue.queue(),
index = $.inArray( doRequest, queue );
if ( index > -1 ) {
queue.splice( index, 1 );
}
// and then reject the deferred
dfd.rejectWith( ajaxOpts.context || ajaxOpts,
[ promise, statusText, "" ] );
return promise;
};
// run the actual query
function doRequest( next ) {
jqXHR = $.ajax( ajaxOpts )
.then( next, next )
.done( dfd.resolve )
.fail( dfd.reject );
}
return promise;
};
// !!!!!!!!!!!!!!!!!
// this is what the developer suggested on his website in the comments section
// ... but it does not appear to work
$.ajaxQueue.stop = function( clear ) { ajaxQueue.stop( clear ); }
})(jQuery);
Thank for your efforts in helping me to solve the problem. However..
I have found a better ajax queue plugin – “ajaxq” by Oleg Podolsky, if you need to queue ajax requests (along with the ability to properly clear the queue), I recommend using this instead.
Add to Queue:
Stop / Clear Queue:
Plugin: