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
throttle
that is assigned an anonymous function that takes in two parametersfunc
anddelay
and returns aFunction
.let isThrottled: boolean: This line declares a variable named
isThrottled
that is assigned a value of typeboolean
.return function(): This line returns an anonymous function.
const context = this: This line declares a constant named
context
that is assigned the value ofthis
.const args = arguments: This line declares a constant named
args
that is assigned the value ofarguments
.if (!isThrottled): This line checks if
isThrottled
isfalse
.func.apply(context, args): This line calls the
func
function and passes in thecontext
andargs
as parameters.isThrottled = true: This line assigns the value
true
toisThrottled
.setTimeout(() => { isThrottled = false }, delay): This line calls the
setTimeout()
function and passes in an anonymous function that assigns the valuefalse
toisThrottled
and thedelay
as 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.