Magicsheet logo

Debounce

Medium
65%
Updated 6/1/2025

Topics

Debounce

What is this problem about?

The Debounce interview question is a classic front-end and system design task. You need to implement a function that accepts a callback and a delay time t. The debounced function should ensure that the callback is only executed after t milliseconds have passed since the last time the debounced function was called. This is used to limit the frequency of expensive operations like API calls during a window resize or keypress event. This Debounce coding problem is a test of your understanding of timers and closures.

Why is this asked in interviews?

Tech companies like Meta and Google ask this because debouncing is a critical performance optimization in real-world web applications. It tests your knowledge of Asynchronous Programming, Closures, and the this context in JavaScript. It evaluates whether you can manage state (the timer ID) across multiple function calls.

Algorithmic pattern used

This problem relies on the Timer and Closure pattern.

  1. State Management: Use a variable inside the outer function's scope to store the timeoutID.
  2. Reset Logic: Every time the debounced function is invoked, immediately clear the existing timeout using clearTimeout(timeoutID).
  3. Scheduling: Set a new timeout using setTimeout that will execute the original callback after t milliseconds.
  4. Context preservation: Ensure the callback is called with the correct this context and arguments using .apply() or .call().

Example explanation

Imagine a search bar that calls an API on every keystroke.

  1. User types "H" at 0ms. A timer starts for 500ms.
  2. User types "e" at 200ms. The first timer is cancelled, and a new 500ms timer starts.
  3. User types "l" at 400ms. The second timer is cancelled, and a third 500ms timer starts.
  4. User stops typing. At 900ms (400ms + 500ms), the API call for "Hel" is finally sent.

Common mistakes candidates make

  • Not clearing the timeout: If you don't call clearTimeout, every single keystroke will eventually trigger the callback, defeating the purpose of debouncing.
  • Losing arguments: Forgetting to pass the arguments received by the debounced function to the original callback.
  • Timer leakage: Not returning the timeoutID or failing to clean up when the component unmounts (though the implementation itself usually doesn't require this).

Interview preparation tip

Understand the difference between Debounce (wait for a pause) and Throttle (execute at most once every X ms). Interviewers often ask you to compare the two or implement both.

Similar Questions