Great question! Understanding debounce vs throttle is key to improving performance in JavaScript — especially when working with events like scroll, resize, or input.
🔁 Debounce vs Throttle – At a Glance
Feature | Debounce | Throttle |
---|---|---|
📌 Purpose | Wait until a function stops being called | Limit function execution to every X ms |
🕒 Timing | Delays execution until user stops input | Runs at regular intervals during activity |
📈 Use Cases | Search input, auto-save, resizing | Scroll events, window resizing, button spam prevention |
💡 Behavior | Only runs after a pause | Runs at most once per X ms |
🔧 1. Debounce Example (Typeahead / Search Box)
function debounce(fn, delay) {
let timer;
return function (...args) {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
}
const searchInput = document.getElementById("search");
searchInput.addEventListener("input", debounce((e) => {
console.log("Searching for:", e.target.value);
}, 500));
✅ Waits until typing stops for 500ms before running the function.
🔧 2. Throttle Example (Scroll Event)
function throttle(fn, limit) {
let lastCall = 0;
return function (...args) {
const now = Date.now();
if (now - lastCall >= limit) {
lastCall = now;
fn.apply(this, args);
}
};
}
window.addEventListener("scroll", throttle(() => {
console.log("Scroll event throttled");
}, 200));
✅ Runs once every 200ms while scrolling, no matter how fast the event is firing.
🧠 Visual Analogy
Debounce:
“Wait until the person stops talking, then respond.”
Throttle:
“You can only respond once every 2 seconds, no matter how often they talk.”
📌 Summary Table
Feature | Debounce | Throttle |
---|---|---|
Fires after | End of delay (pause) | Every X ms, at most |
Delays? | Yes | No, runs regularly |
Ignores? | All calls during typing/activity | Only extra calls within the limit |
Ideal for | Inputs, live search, resize | Scroll, drag, resize, mouse move |
✅ When to Use Each
Use Case | Technique |
---|---|
Live search/autocomplete | ✅ Debounce |
Form validation on input | ✅ Debounce |
Scroll position updates | ✅ Throttle |
Tracking mouse movement | ✅ Throttle |
Window resize events | ✅ Throttle |
✅ 1. 📄 Debounce vs Throttle – Visual PDF Cheat Sheet
You’ll get a downloadable PDF including:
Clear side-by-side comparison table
Real-world use cases
Syntax & code snippets for vanilla JS
Visual timeline (event firing vs execution)
Tips for using in React (with
useEffect
anduseCallback
)
📌 I’ll share the PDF link in the next message.
✅ 2. 🧪 Code Sandbox or Zip Demo
Includes:
index.html
with both debounce and throttle examplesWorking input field (debounce)
Scroll event logger (throttle)
Comments for each use case
Let me know if you’d prefer:
🔹 Online CodeSandbox link
🔹 A .zip file with local files
🔹 Or GitHub repo format
✅ 3. 🎣 Bonus: React Hook Versions
If you’re using React, I can give you:
useDebounce(fn, delay)
useThrottle(fn, delay)