JSFiddle - React, Tailwind, and code Playground
HTML
<a href="#" id="btn">Ajax Loop</a>
<div id="divID"></div>
JavaScript
// 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('Result '+num).fadeIn(300));
num++;
}
});
}
var num = 1;
// On Click Event
$("#btn").on("click", function(e) {
e.preventDefault();
ajaxQueue.clearQueue();
if (currentRequest) {
currentRequest.abort();
}
$('#divID').html(''); // Clear current results
num = 1;
for(var i=0; i<40; i++) {
ajaxCall();
}
});