Skip to content

Instantly share code, notes, and snippets.

@acemir
Last active March 21, 2016 07:59
Show Gist options
  • Save acemir/91c8eac579d7e47570fa to your computer and use it in GitHub Desktop.
Save acemir/91c8eac579d7e47570fa to your computer and use it in GitHub Desktop.
Waits multiple ajax calls response
var MyRequestsCompleted = (function() {
var numRequestToComplete, requestsCompleted, callBacks, singleCallBack;
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);
};
};
})();
// Usage
var requestCallback = new MyRequestsCompleted({
numRequest: 10, // number of requests
singleCallback: function(){
// All fired
}
});
// After response of each ajax in a loop
requestCallback.requestComplete(true);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment