Performance optimization is a key part of frontend development, especially when handling rapid user interactions like typing, scrolling, or button clicks. That’s where two powerful techniques come into play — Debouncing and Throttling.
But these words sound fancy, right?
So let me break them down for you in a simple story involving a little girl and her mom — a story you’ll never forget 😉
👧 Debouncing — “Ask only after you stop asking!”
🧠 Real-World Scenario:
Imagine a little girl (the user) wants a candy (API call), and she keeps bugging her mom (the system) every few seconds:
“Mom, can I have candy? Can I have candy? Can I have candy?”
Mom gets overwhelmed. So she says:
“Ask me only once after you’re done talking for 5 seconds!”
Now, every time the girl opens her mouth again, the 5-second timer resets.
Finally, when she stays quiet for 5 seconds, mom gives her the candy 🍬
That’s Debouncing!
🔁 It waits for the last request, and only proceeds after the user stops asking for a while.
💻 Debounce Code Example
Debounce Example
let count = 0;
function getData() {
console.log('Function called ' + count++);
}
const myDebounce = (fn, delay) => {
let timer;
return function(...args) {
if (timer) clearTimeout(timer); // Clear previous request
timer = setTimeout(() => {
fn();
}, delay); // Wait until user stops
};
};
let betterFunction = myDebounce(getData, 1000);
Enter fullscreen mode
Exit fullscreen mode
👧 Throttling — “You’ll get it, but only once in a while!”
Now let’s return to our girl and her candy.This time, mom sets a rule:
“You’ll get only one candy every 10 minutes. Don’t keep asking!”
So if the girl asks at:
Minute 1 ❌ (Ignored)
Minute 3 ❌ (Ignored)
Minute 7 ❌ (Ignored)
Minute 10 ✅ (Gets candy!)
That’s Throttling!
🔁 It ensures that a function runs at most once in a specific time interval, even if it’s triggered many times.
💻 Throttle Polyfill Example
const myThrottle = (cb, delay) => {
let last = 0;
return (...args) => {
let now = new Date().getTime();
if (now - last < delay) return; // Ignore request if too soon
last = now;
return cb(...args);
};
};
Enter fullscreen mode
Exit fullscreen mode
🔄 Debounce vs Throttle — In a Nutshell