Last active
September 6, 2022 10:38
-
-
Save vinchik/c21b2cadd42530ef40a4e77dae756dd7 to your computer and use it in GitHub Desktop.
throttle
This file contains hidden or 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
// 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