Created
March 29, 2021 16:29
-
-
Save james2doyle/9ff5efa802f84594313160f6d811b917 to your computer and use it in GitHub Desktop.
Throttle will make sure a function is only called once within the given amount of time
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
/** | |
* Throttle will make sure a function is only called once within the given amount of time | |
* must use function to keep `this` context | |
*/ | |
function throttle(fn: Function, threshold: number = 250) { | |
// check function | |
if (typeof fn !== 'function') { | |
throw new TypeError('You must provide a function as the first argument for throttle.'); | |
} | |
// check threshold | |
if (typeof threshold !== 'number') { | |
throw new TypeError('You must provide a number as the second argument for throttle.'); | |
} | |
let lastEventTimestamp: number | null = null; | |
return (...args: any) => { | |
const now = Date.now(); | |
if (lastEventTimestamp === null || now - lastEventTimestamp >= threshold) { | |
lastEventTimestamp = now; | |
fn.apply(this, args); | |
} | |
}; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment