Skip to content

Instantly share code, notes, and snippets.

@GoodBoyDigital
Created February 16, 2020 21:05
Show Gist options
  • Save GoodBoyDigital/74a3769f472f9af30554349eaa9c1650 to your computer and use it in GitHub Desktop.
Save GoodBoyDigital/74a3769f472f9af30554349eaa9c1650 to your computer and use it in GitHub Desktop.
TS Throttle function
const throttleMap = new Map<Function, {throttledFunction: Function; args: any[]}>();
/**
* Lets you call a function and have it throttled by a certain delay.
* Useful for when a function may be spammed!
*
* @example
* ```
* function resize(w, h){
* console.log('resized', w, h);
* }
*
* window.onResize = ()=>{
* throttle(resize, 100)(window.innerWidth, window.innerHeight);
* }
* ```
*
* @param fun the function you want throttled
* @param delay how long until the function is executed
*/
export function throttle(fun: Function, delay = 100, scope?: any): Function
{
if (!throttleMap.has(fun))
{
const throttledFunction = (...args): void =>
{
throttleMap.get(fun).args = args;
setTimeout(() =>
{
const latestArgs = throttleMap.get(fun).args;
if (scope)
{
fun.call(scope, ...latestArgs);
}
else
{
fun(...latestArgs);
}
}, delay);
};
throttleMap.set(fun, { throttledFunction, args: null });
}
return throttleMap.get(fun).throttledFunction;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment