Skip to content

Instantly share code, notes, and snippets.

@louiszuckerman
Created June 6, 2013 21:52
Show Gist options
  • Save louiszuckerman/5725311 to your computer and use it in GitHub Desktop.
Save louiszuckerman/5725311 to your computer and use it in GitHub Desktop.
Queue to manage ajax requests (made for angularjs $resource objects)
/*
Example usage:
ajaxEnqueue(Resource.get, {id: 1}, function(val) {console.log("API returned "+val)"})
Where Resource is an angular $resource object.
This queue will throttle AJAX requests so that only a limited number (ajaxParallel) are in flight at a time.
*/
//TODO: Encapsulate this in a service object, get rid of globals.
var ajaxQueue = [];
var ajaxParallel = 10;
var ajaxOutstanding = 0;
function ajaxEnqueue(method, params, success, failure) {
ajaxQueue.push(function() {
method(params, function(val) {
if (typeof(success) == "function") {
success(val);
}
ajaxOutstanding--;
ajaxDequeue();
}, function(val) {
if (typeof(failure) == "function") {
failure(val);
}
ajaxOutstanding--;
ajaxDequeue();
});
});
ajaxDequeue();
}
function ajaxDequeue() {
if (ajaxOutstanding < ajaxParallel && ajaxQueue.length > 0) {
ajaxOutstanding++;
ajaxQueue.shift()();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment