Skip to content

Instantly share code, notes, and snippets.

@nathanaelnsmith
Created July 28, 2017 18:07
Show Gist options
  • Save nathanaelnsmith/e10260640cae052dbde23c859c18cbbb to your computer and use it in GitHub Desktop.
Save nathanaelnsmith/e10260640cae052dbde23c859c18cbbb to your computer and use it in GitHub Desktop.
Throttle calling a provided function on every element in the calling array.
function throttle(set, limit, threshold, callback) {
let timer = 0;
window.setInterval(() => {
timer++;
}, threshold);
let i = 0;
let requestChunk = timer;
let requestsSent = 0;
while (i < set.length) {
// requests within limit
if (requestChunk === timer && requestsSent < limit) {
callback(set[i]);
requestsSent++;
i++;
} else if (requestChunk === timer && requestsSent >= limit) {
// request outside of limit
console.log('outside limit');
requestChunk = timer;
requestsSent = 0;
}
if (requestChunk !== timer) {
// chunk reset
console.log('next chunk');
requestChunk = timer;
requestsSent = 0;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment