Skip to content

Instantly share code, notes, and snippets.

@malle-pietje
Forked from Terrance/AjaxQueue.js
Created February 2, 2018 09:21
Show Gist options
  • Save malle-pietje/d51dceae3bb470962eb836abe1740ee0 to your computer and use it in GitHub Desktop.
Save malle-pietje/d51dceae3bb470962eb836abe1740ee0 to your computer and use it in GitHub Desktop.
Limit concurrent jQuery ajax requests to at most 3 at a time, and queue the rest.
var ajaxReqs = 0;
var ajaxQueue = [];
var ajaxActive = 0;
var ajaxMaxConc = 3;
function addAjax(obj) {
ajaxReqs++;
var oldSuccess = obj.success;
var oldError = obj.error;
var callback = function() {
ajaxReqs--;
if (ajaxActive === ajaxMaxConc) {
$.ajax(ajaxQueue.shift());
} else {
ajaxActive--;
}
}
obj.success = function(resp, xhr, status) {
callback();
if (oldSuccess) oldSuccess(resp, xhr, status);
};
obj.error = function(xhr, status, error) {
callback();
if (oldError) oldError(xhr, status, error);
};
if (ajaxActive === ajaxMaxConc) {
ajaxQueue.push(obj);
} else {
ajaxActive++;
$.ajax(obj);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment