Throttle vs Debounce

Regular Responder vs. Polite Listener

Allen Kim
2 min readSep 19, 2021
Photo by Laura Ockel on Unsplash

Throttle 1 Second

Hello, I am a robot. As long as you keep calling me, I will answer you but 1 second each. I just love to reply at exact intervals. It would be like this;

Annoying Me: Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi ..….
Throttle Robot: Hi ……… Hi ……… Hi ……… Hi ……… Hi …………

function throttle(func, interval = 500) {
let isRunning;
return function(...args) {
let context = this;
if (!isRunning) {
isRunning = true;
func.apply(context, args);
setTimeout( _ => isRunning = false, interval);
}
};
}

Debounce 1 Second

Hi, I am a robot. As long as you keep calling me, I will answer you but exactly 1 second after you stop calling me. I just don’t like to interrupt you. It would be like this;

Annoying Me: Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi Hi ……....
Debounce Robot: ……………………………………………………..… Hi

function debounce(func, wait = 1000) {
var timeout;
return function (...args) {
var context = this;
var later = function () {
timeout = null;
func.apply(context, args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}

The following is a visualized demo of debounce vs throttle.

For those who do want a simpler implementation of a single-page application without writing JavaScript, I have created a custom element called elements-x, a collection of custom elements. It’s style-customizable and independent from a framework. To know more elements-x, please visit the Github repository.

Do you think this is useful? If so please;
* Leave a message in the comments

* Follow Allen on Twitter (@allenhwkim)

Happy Coding :)

Allen Kim

--

--