JSFiddle - React, Tailwind, and code Playground
by AndrewZhang
HTML
<div id="log"></div>
<button id="ajaxBtn" data-count="0">trigger ajax</button>
JavaScript
;(function($) {
$.ajaxQueue = {
requests: new Array(),
offer: function(options) {
var _self = this,
xhrOptions = $.extend({}, options, {
complete: function(jqXHR, textStatus) {
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) {
// $('#log').append('<p>an ajax request cancelled</p>');
_self.poll();
return ret;
}
}
});
this.requests.push(xhrOptions);
if(this.requests.length == 1) {
$.ajax(xhrOptions);
}
},
poll: function() {
if(this.isEmpty()) {
return null;
}
var processedRequest = this.requests.shift();
var nextRequest = this.peek();
if(nextRequest != null) {
$.ajax(nextRequest);
}
return processedRequest;
},
peek: function() {
if(this.isEmpty()) {
return null;
}
var nextRequest = this.requests[0];
return nextRequest;
},
isEmpty: function() {
return this.requests.length == 0;
}
}
})(jQuery);
$('#ajaxBtn').click(function() {
var count = parseInt($(this).attr('data-count'));
$(this).attr('data-count', ++count);
$(this).html('trigger ajax ' + count);
$.ajaxQueue.offer({
...