The task is to implement a debounce method. A debounce is used to control how often a function is invoked.
The boilerplate code is
function debounce(func, wait) {
// your code here
}
First, a variable to keep track of the timer(period of delay) is created
let timeoutId
A function that will be returned when the timer is set is then created. The function checks if there's an existing timer, and clears it. After the timer is set, the original function is called after the delay period.
return function (...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args);
}, wait);
};
The final code is:
function debounce(func, wait) {
// your code here
let timeoutId;
return function(...args) {
const context = this;
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
func.apply(context, args)
}, wait)
}
}
That's all folks!
Top comments (0)