Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save HelgaZhizhka/8449280f483a662654da7ec592ec7230 to your computer and use it in GitHub Desktop.
Save HelgaZhizhka/8449280f483a662654da7ec592ec7230 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