Skip to content

Instantly share code, notes, and snippets.

@davidisnotnull
Created May 23, 2018 10:45
Show Gist options
  • Save davidisnotnull/6791ed4f9cf99425c5bd74b1ce0fbfbb to your computer and use it in GitHub Desktop.
Save davidisnotnull/6791ed4f9cf99425c5bd74b1ce0fbfbb to your computer and use it in GitHub Desktop.
Queue ajax requests in Javascript
$(function() {
var initialLoad = 0;
var AjaxRequestsCompleted = (function() {
var numRequestToComplete,
requestsCompleted,
callBacks;
return function(options) {
if (!options) options = {};
numRequestToComplete = options.numRequest || 0;
requestsCompleted = options.requestsCompleted || 0;
callBacks = [];
var fireCallbacks = function() {
for (var i = 0; i < callBacks.length; i++) callBacks[i]();
};
if (options.singleCallback) callBacks.push(options.singleCallback);
this.addCallbackToQueue = function(isComplete, callback) {
if (isComplete) requestsCompleted++;
if (callback) callBacks.push(callback);
if (requestsCompleted === numRequestToComplete) fireCallbacks();
};
this.requestComplete = function(isComplete) {
if (isComplete) requestsCompleted++;
if (requestsCompleted === numRequestToComplete) fireCallbacks();
};
this.setCallback = function(callback) {
callBacks.push(callback);
};
};
})();
});
// Example of queue implementation
$("#TriggerId")
.change(function(e) {
e.preventDefault();
var requestCallback = new AjaxRequestsCompleted({
numRequest: 4
});
if (initialLoad === 1) {
// Use this to check if the Ajax call has already run before
// and implement anything
}
$.ajax({
url: "url",
data: {
format: 'json',
id: triggerId
},
type: "POST",
success: function(data) {
requestCallback.addCallbackToQueue(true,
function() {
// Do something on success
});
},
error: function() {
console
.log("It's worse than that, he's dead Jim.");
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment