Throttle
What does throttle do?
It throttles the function 😀👍
/**
* Throttle in TypeScript
* @param func Function to be throttled
* @param delay Number of milliseconds to delay
* @returns A new function that wraps the given function
*/
const throttle: (func: Function, delay: number) => Function = (func, delay) => {
let isThrottled: boolean;
return function() {
const context = this;
const args = arguments;
if (!isThrottled) {
func.apply(context, args);
isThrottled = true;
setTimeout(() => {
isThrottled = false
}, delay);
}
}
}
How does it work?
const throttle: (func: Function, delay: number) => Function = (func, delay): This line declares a constant named
throttlethat is assigned an anonymous function that takes in two parametersfuncanddelayand returns aFunction.let isThrottled: boolean: This line declares a variable named
isThrottledthat is assigned a value of typeboolean.return function(): This line returns an anonymous function.
const context = this: This line declares a constant named
contextthat is assigned the value ofthis.const args = arguments: This line declares a constant named
argsthat is assigned the value ofarguments.if (!isThrottled): This line checks if
isThrottledisfalse.func.apply(context, args): This line calls the
funcfunction and passes in thecontextandargsas parameters.isThrottled = true: This line assigns the value
truetoisThrottled.setTimeout(() => { isThrottled = false }, delay): This line calls the
setTimeout()function and passes in an anonymous function that assigns the valuefalsetoisThrottledand thedelayas parameters.
Overall, the throttle function takes in a function and a delay as arguments and returns a throttled version of that function. A throttled function is a function that can only be called once every delay milliseconds.