JSFiddle - React, Tailwind, and code Playground
HTML
<button href="#" id="btn-start">Start</button> <button href="#" id="btn-stop">Stop</button>
<div id="divID"></div>
JavaScript
// not my code, this is community developed, thanks to stackoverflow
// http://stackoverflow.com/questions/16775447/jquery-dequeue-an-ajaxqueue
// forked from sroes' jsfiddle from accepted answer
// jQuery on an empty object, we are going to use this as our queue
var ajaxQueue = $({});
var currentRequest = null;
$.ajaxQueue = function( ajaxOpts ) {
// Hold the original complete function.
var oldComplete = ajaxOpts.complete;
// Queue our ajax request.
ajaxQueue.queue(function( next ) {
// Create a complete callback to fire the next event in the queue.
ajaxOpts.complete = function() {
// Fire the original complete if it was there.
if ( oldComplete ) {
oldComplete.apply( this, arguments );
}
// Run the next query in the queue.
next();
};
// Run the query.
currentRequest = $.ajax( ajaxOpts );
});
};
// Ajax Call
function ajaxCall() {
$.ajaxQueue({
type: "POST",
url: '/echo/json/',
async: true,
cache: false,
success: function( result ) {
$('#divID').append($('<div/>').html('Call '+num).fadeIn(300));
if(num == total) {
$('#divID').append($('<div/>').html('All Done').fadeIn(300));
}
num++;
}
});
}
// Abort method
function abortAjaxQueue() {
ajaxQueue.clearQueue();
if (currentRequest) {
currentRequest.abort();
}
}
// test code
var num = 1;
var total = 30;
// clears all the pending entries and currently running request
$("#btn-stop").on("click", function(e) {
abortAjaxQueue();
});
// a sample use case
$("#btn-start").on("click", function(e) {
e.preventDefault();
abortAjaxQueue();
$('#divID').html('');
num = 1;
for(var i=0; i<total; i++) {
ajaxCall();
}
});