JSFiddle - React, Tailwind, and code Playground
by AndrewZhang
HTML
<div id="log"></div>
<button id="ajaxBtn" data-count="0">trigger ajax</button>
JavaScript
;(function($) {
function AjaxQueue(override) {
this.override = !!override;
};
AjaxQueue.prototype = {
requests: new Array(),
offer: function(options) {
var _self = this;
var xhrOptions = $.extend({}, options, {
complete: function(jqXHR, textStatus) {
if($.isArray(options.complete)) {
var funcs = options.complete;
for(var i = 0, len = funcs.length; i < len; i++)
funcs[i].call(this, jqXHR, textStatus);
} else {
if(options.complete)
options.complete.call(this, jqXHR, textStatus);
}
_self.poll();
},
beforeSend: function(jqXHR, settings) {
if(options.beforeSend)
var ret = options.beforeSend.call(this, jqXHR, settings);
if(ret === false) {
_self.poll();
return ret;
}
}
});
if(this.override) {
console.log('go override');
this.replace(xhrOptions);
} else {
console.log('go queue');
this.requests.push(xhrOptions);
if(this.requests.length == 1) {
$.ajax(xhrOptions);
}
}
},
replace: function(xhrOptions) {
var prevRet = this.peek();
if(prevRet != null) {
prevRet.abort();
}
this.requests.shift();
this.requests.push($.ajax(xhrOptions));
},
poll: function()...