Debounce and Throttle in JS

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

--

--

--

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
Aditya Mhamunkar

Aditya Mhamunkar

Software Engineer — Frontend

More from Medium

Angular vs. React comparison

Context and ‘this’ Basics in JS

Async Programming with Callbacks, Promises, and Async/Await -Part 1-

Synchronous vs Asynchronous Operations

Basic of Redux — A beginner Guide