← Back to libraryQuestion 165 of 468
🧩JavaScript CodingAdvanced

Implement Debounce

📌 Definition:

Write a debounce(fn, delay) utility that delays calling fn until 'delay' ms have passed since the last invocation.

📖 Detailed Explanation:

Keep a timer in a closure. Each call clears the pending timer and schedules a new one, so fn runs only after a quiet gap. Preserve 'this' and arguments so it works as a method or event handler.

💻 Solutions:
function debounce(fn, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => fn.apply(this, args), delay);
  };
}
// const onSearch = debounce(query => api.search(query), 300);
🔑 Key Points:
  • Closure holds the timer across calls
  • clearTimeout + setTimeout resets the wait each call
  • fn.apply(this, args) preserves context and arguments
  • Debounce = 'run after they stop'; throttle = 'run at a fixed rate'
🌍 Real-World Example:

Debouncing a search-as-you-type handler turns dozens of keystroke API calls into a single call after the user pauses — critical for both UX and rate limits.

🎯 Scenario-Based Interview Question:

Someone writes const onScroll = debounce(handler, 200) but passes handler.bind(obj) and loses live 'this'. Why does using an arrow inside debounce matter?