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
debounce
that takes in two parametersfunc
anddelay
and returns aFunction
.let timer = null: This line declares a variable named
timer
that is assigned the valuenull
.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
.clearTimeout(timer): This line calls the
clearTimeout()
function and passes in thetimer
as a parameter.timer = setTimeout(() => { func.apply(context, args) }, delay): This line assigns the value of the
setTimeout()
function totimer
and passes in an anonymous function that calls thefunc
function and passes in thecontext
andargs
as parameters and thedelay
as 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.