Skip to content

Instantly share code, notes, and snippets.

@james2doyle
Created March 29, 2021 16:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save james2doyle/9ff5efa802f84594313160f6d811b917 to your computer and use it in GitHub Desktop.
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
/**
* 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