Skip to content

Instantly share code, notes, and snippets.

@nczz
Forked from pavelmaca/jquery.ajax.queue.example.js
Created October 20, 2022 03:56
Show Gist options
  • Save nczz/a81815de0952ba4c33c5726e16b7b823 to your computer and use it in GitHub Desktop.
Save nczz/a81815de0952ba4c33c5726e16b7b823 to your computer and use it in GitHub Desktop.
jQuery AJAX Queue
/**
* HOW-TO
*/
// same param as $.ajax(option); see http://api.jquery.com/jQuery.ajax/
$.ajaxQueue.addRequest(option);
// start processing one by one requests
$.ajaxQueue.run();
// stop at actual position @TODO use .pause() instend
$.ajaxQueue.stop();
//delete all unprocessed requests from cache
$.ajaxQueue.clear();
/**
* Plugin for using queue for multiple ajax requests.
*
* @autor Pavel Máca
* @github https://github.com/PavelMaca
* @license MIT
*/
(function($) {
var AjaxQueue = function(options){
this.options = options || {};
var oldComplete = options.complete || function(){};
var completeCallback = function(XMLHttpRequest, textStatus) {
(function() {
oldComplete(XMLHttpRequest, textStatus);
})();
$.ajaxQueue.currentRequest = null;
$.ajaxQueue.startNextRequest();
};
this.options.complete = completeCallback;
};
AjaxQueue.prototype = {
options: {},
perform: function() {
$.ajax(this.options);
}
}
$.ajaxQueue = {
queue: [],
currentRequest: null,
stopped: false,
stop: function(){
$.ajaxQueue.stopped = true;
},
run: function(){
$.ajaxQueue.stopped = false;
$.ajaxQueue.startNextRequest();
},
clear: function(){
$.ajaxQueue.queue = [];
$.ajaxQueue.currentRequest = null;
},
addRequest: function(options){
var request = new AjaxQueue(options);
$.ajaxQueue.queue.push(request);
$.ajaxQueue.startNextRequest();
},
startNextRequest: function() {
if ($.ajaxQueue.currentRequest) {
return false;
}
var request = $.ajaxQueue.queue.shift();
if (request) {
$.ajaxQueue.currentRequest = request;
request.perform();
}
}
}
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment