Skip to content

Instantly share code, notes, and snippets.

@vinchik
Last active September 6, 2022 10:38
Show Gist options
  • Save vinchik/c21b2cadd42530ef40a4e77dae756dd7 to your computer and use it in GitHub Desktop.
Save vinchik/c21b2cadd42530ef40a4e77dae756dd7 to your computer and use it in GitHub Desktop.
throttle
// Creates a throttled function that only invokes "originalFn" at most once per every "delayMs" milliseconds
function throttle(originalFn, delayMs) {
let timeout; // timeout to keep track of the executions
return (...args) => {
if (timeout) { // if timeout is set, this is NOT the first execution, so ignore
return;
}
// this is the first execution which we need to delay by "delayMs" milliseconds
timeout = setTimeout(() => {
originalFn(...args); // call the passed function with all arguments
timeout = null; // reset timeout so that the subsequent call launches the process anew
}, delayMs);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment