Debounce & Throttle: Classic Interview Implementations
JS جاوااسکریپت

Debounce & Throttle: Classic Interview Implementations

Implement scroll, resize, and search-input handlers correctly — a practical question with real production impact.

BugCast Admin··۵ دقیقه مطالعه

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 AbortController for stale requests

  • Lodash implementations support leading and trailing edges

  • Mention UX: 200–300ms debounce is typical for typeahead

#debounce#throttle#interview

مطالب مرتبط