Debounce and throttle control how often expensive handlers run. Search autocomplete uses debounce; scroll tracking often uses throttle.
Common Interview Questions
Q: What is debouncing?
Answer: Debounce delays execution until the user stops triggering the event for a specified wait period. Each new trigger resets the timer.
function debounce(fn, wait) {
let timer;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn(...args), wait);
};
}
Q: What is throttling?
Answer: Throttle ensures the function runs at most once per interval, regardless of how many events fire. Useful for scroll, resize, and mousemove.
function throttle(fn, limit) {
let inThrottle = false;
return (...args) => {
if (inThrottle) return;
fn(...args);
inThrottle = true;
setTimeout(() => { inThrottle = false; }, limit);
};
}
Q: Debounce vs throttle for a search box?
Answer: Debounce — you want the API call only after typing pauses. Throttle would fire mid-typing on a fixed schedule, wasting requests and showing stale partial queries.
Q: How do you add a leading-edge option to debounce?
Answer: Track whether the wait window is active. On first call in a quiet period, invoke immediately; subsequent calls within wait only schedule the trailing call.
Key Points for Interviews
-
Debounce: wait for pause; throttle: cap frequency
-
Always clear timers on cleanup in React
useEffect -
Pair debounced search with
AbortControllerfor stale requests -
Lodash implementations support
leadingandtrailingedges -
Mention UX: 200–300ms debounce is typical for typeahead
