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

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

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

--

--

Software Engineer at Meta

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store