Debounce and Throttle in JS

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);
}
}

--

--

Software Engineer — Frontend

Love podcasts or audiobooks? Learn on the go with our new app.

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