Debounce vs Throttle in JavaScript
Compare debounce and throttle in JavaScript, learn when to use each for search inputs and scroll handlers, and see clean closure-based implementations.
Expected Interview Answer
Debounce and throttle are two techniques for limiting how often a function runs in response to frequent events; debounce waits until activity stops before running once, while throttle runs at most once per fixed interval during activity.
Debounce resets a timer on every call and only invokes the function after a quiet period elapses — ideal for search-as-you-type or validating input after the user pauses. Throttle guarantees the function runs on a steady cadence no matter how many events fire — ideal for scroll, resize, or mousemove handlers where you want regular but capped updates. Both are typically implemented with closures over a timer or timestamp.
- Prevents expensive work from running on every rapid event
- Debounce collapses a burst into a single trailing call
- Throttle guarantees a steady, capped update rate
- Reduces API calls, reflows, and CPU usage
- Improves responsiveness and battery life on the client
AI Mentor Explanation
Debounce is like a batter who waits for the bowler to finish a whole flurry of feints and only plays once the ball is truly delivered; throttle is like the strike clock allowing one scored update every fixed number of seconds no matter how many quick singles are attempted.
Step-by-Step Explanation
Step 1
Identify the trigger
Find the high-frequency event: keystrokes, scroll, resize, or mousemove that fire many times per second.
Step 2
Choose the pattern
Use debounce when you only care about the final state after activity stops; use throttle when you want regular updates during activity.
Step 3
Debounce with a resettable timer
On each call, clear the previous timer and set a new one; the function runs only after the delay passes with no new calls.
Step 4
Throttle with a gate
Track the last run time (or a boolean flag); ignore calls until the interval has elapsed, then run and reset the gate.
Step 5
Clean up
Clear pending timers on unmount or when removing the listener to avoid stale calls and leaks.
What Interviewer Expects
- A precise definition of each and how they differ
- Correct use cases: search input for debounce, scroll for throttle
- Ability to implement both with closures and timers
- Understanding of leading vs trailing invocation
- Awareness of cleanup to avoid stale or leaked timers
Common Mistakes
- Using the two terms interchangeably
- Debouncing a scroll handler when steady updates are needed
- Forgetting to clear the timer, causing stale invocations
- Recreating the debounced function on every render so it never delays
- Ignoring leading versus trailing edge behaviour
Best Answer (HR Friendly)
“Both debounce and throttle stop a function from running too often when an event fires rapidly. Debounce waits until the activity stops and then runs once, which suits search boxes; throttle lets it run at a steady, limited rate while activity continues, which suits scrolling.”
Code Example
function debounce(fn, delay) {
let timer
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => fn.apply(this, args), delay)
}
}
function throttle(fn, interval) {
let last = 0
return function (...args) {
const now = Date.now()
if (now - last >= interval) {
last = now
fn.apply(this, args)
}
}
}
// Usage
searchInput.addEventListener('input', debounce(runSearch, 300))
window.addEventListener('scroll', throttle(onScroll, 200))Follow-up Questions
- How would you add leading-edge invocation to a debounce?
- When is throttle a better choice than debounce?
- How do you cancel a pending debounced call?
- Why should the debounced function be created once, not on every render?
- How would you implement throttle using setTimeout instead of timestamps?
MCQ Practice
1. Which technique runs the function only after events stop firing for a set delay?
Debounce resets its timer on each call and invokes the function only after a quiet period, collapsing a burst into one call.
2. For a scroll handler that should update at a steady, capped rate, you should use:
Throttle guarantees the handler runs at most once per interval during continuous scrolling, giving regular updates.
3. A common bug is recreating a debounced function on every render because:
Each new instance has a fresh timer, so the closure that tracks the delay is discarded before it can fire.
Flash Cards
What does debounce do? — Delays running a function until events stop firing for a set period, then runs it once.
What does throttle do? — Runs a function at most once per fixed interval while events keep firing.
Best use for debounce? — Search-as-you-type or input validation after the user pauses typing.
Best use for throttle? — Scroll, resize, or mousemove handlers needing regular but capped updates.