Skip to content

Instantly share code, notes, and snippets.

@raykendo

raykendo/file.js

Last active Mar 14, 2018
Embed
What would you like to do?
Throttle Ajax Requests
(function () {
// ajax function from https://gist.github.com/Xeoncross/7663273
function ajax(url, callback, data, x) {
try {
x = new (this.XMLHttpRequest || ActiveXObject)("MSXML2.XMLHTTP.3.0");
x.open(data ? "POST" : "GET", url, 1);
x.setRequestHeader("X-Requested-With", "XMLHttpRequest");
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
x.onreadystatechange = function () {
x.readyState > 3 && callback && callback(x.responseText, x);
};
x.send(data);
} catch (e) {
window.console && console.log(e);
}
}
/**
* Throttles ajax calls rather than calling all at once
* @param {string[]} listOfUrls - a list of URLS
* @param {function} callback - callback function once all URLS have been called
* @param {object[]} [results] - optional list of previous results. Initially null.
*/
function ajaxCallThrottle(listOfUrls, callback, results) {
var url;
// if results not set, should be an empty list.
results = results || [];
// if list of urls is null or an empty list (or not a list), run the callback and stop;
if (!listOfUrls || !listOfUrls.length || typeof listOfUrls.shift !== 'function') {
callback(results);
return;
}
// pull the url off the top of the list of URLS
url = listOfUrls.shift();
ajax(url, function (response) {
results.push(response);
// call the call throttler on the rest of the list.
ajaxCallThrottle(listOfUrls, callback, results);
});
}
// an example
var sites = [
'http://www.yahoo.com/',
'http://www.myspace.com/',
'http://www.digg.com/'
];
ajaxCallThrottle(sites, function (results) {
console.log('Testing if these sites ever go away.');
results.forEach(function (result, i) {
console.log(sites[i], result);
});
});
}());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment