Debounce and Throttle in JS
Debounce and Throttle are techniques to control how many time we allow an event to occur. The difference between them is explained below with an example
Debounce
The Debounce technique allows us to “group” multiple sequential calls in a single one.
function debounce(fn, ms) {
let timeout; return (...args) => {
// clear the previous timeout, if there is
clearTimeout(timeout); // set new timeout
timeout = setTimeout(() => {
fn(...args);
}, ms);
}
}
Throttle
Throttle guarantees the execution of the function regularly, at least every x milliseconds while the event is occurring.
function throttle(fn, ms) {
let timeout;
let latestArgs; return (...args) => {
latest = args;
if (timeout) {
return;
} timeout = setTimeout(()=>{
timeout = undefined;
fn(...latestArgs);
}, ms);
}
}
Throttle and Debounce can be useful in many situations like while the user is typing in the search box and you need to fire ajax event to populate filtered suggestions or for the drag event where you need to perform some action while the user is dragging an element.
I hope this simple post has helped you understand why throttling and debouncing is used and what the difference between them