Debounce
What does debounce do?
It debounces the function 😀👍
/**
* Debounce in TypeScript
* @param func {Function} Function to be debounced
* @param delay {number} Number of milliseconds to delay
* @returns A new function that wraps the given function
*/
function debounce(func: Function, delay: number) {
let timer = null;
return function() {
const context = this;
const args = arguments;
clearTimeout(timer)
timer = setTimeout(() => {
func.apply(context, args);
}, delay)
}
};
How does it work?
function debounce(func: Function, delay: number): This line declares a function named
debouncethat takes in two parametersfuncanddelayand returns aFunction.let timer = null: This line declares a variable named
timerthat is assigned the valuenull.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.clearTimeout(timer): This line calls the
clearTimeout()function and passes in thetimeras a parameter.timer = setTimeout(() => { func.apply(context, args) }, delay): This line assigns the value of the
setTimeout()function totimerand passes in an anonymous function that calls thefuncfunction and passes in thecontextandargsas parameters and thedelayas a parameter.
Overall, the debounce function takes in a function and a delay as arguments and returns a debounced version of that function. A debounced function is a function that can only be called once every delay milliseconds.