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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Debounce Example</title>
</head>
<body>
<textarea id="myInput" onkeyup="betterFunction()"></textarea>
<script>
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);
</script>
</body>
</html>
👧 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.
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);
};
};
🔄 Debounce vs Throttle — In a Nutshell
Top comments (1)
Gotta say, the way you broke this down makes it stick way better for me, especially with those code bits after