Created
July 28, 2017 18:07
-
-
Save natedoesweb/e10260640cae052dbde23c859c18cbbb to your computer and use it in GitHub Desktop.
Throttle calling a provided function on every element in the calling array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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