Write a debounce function with a cancel() method to clear any pending calls and flush() to call the function immediately clear by clearing the last timer.
🔗Debounce 🟡 Medium 🧩 Pattern – JavaScript Essentials
What is debouncing?
Debouncing is a technique that ensures that a function is called only after certain time, if the function is called when the timer is running then the previous timer is cancelled and a new timer is started.
Related: Throttle in JavaScript | Matrixread
What is throttling?
With throttling we are trying to limit the rate at which the function is called.In throtlling we call a function once normally and it can only be called after a certain time, any calls in between are ignored.
Why use function.apply?
With apply() we can pass this (context) and use it inside the function if required. We can also use call() but apply allows passing multiple arguments.
JavaScript Debounce
/**
* @param {Function} func
* @param {number} wait
* @return {Function}
*/
export default function debounce(func, wait) {
let timerId;
let latestArgs;
let latestContext;
function debounced(...args) {
latestArgs = args;
latestContext = this;
if (timerId) {
clearTimeout(timerId);
}
timerId = setTimeout(() => func.apply(latestContext, latestArgs), wait);
}
debounced.cancel = () => {
if (timerId) {
clearTimeout(timerId);
}
timerId = undefined;
};
debounced.flush = () => {
if (timerId) {
func.apply(latestContext, latestArgs);
debounced.cancel();
}
};
return debounced;
}Code language: JavaScript (javascript)