Skip to main content

Search

Search problems, hooks, and pages

Implement Debounce

Implement a debounce function that delays the execution of a callback until after a specified wait time has elapsed since the last time it was invoked. This is one of the most commonly asked JS interview questions — interviewers often follow up by asking for a leading-edge variant or cancel/flush methods.

Examples

Input: debounce(fn, 300) — called 5 times rapidly
Output: fn is called exactly once, 300 ms after the last call
// Each call resets the timer; only the final call completes the wait.
Input: debounce(fn, 300, { leading: true }) — called 3 times in 200 ms
Output: fn is called immediately on the first call; subsequent calls within 300 ms are ignored
// Leading-edge fires on the first call, then locks for the delay period.

Constraints

  • The returned function must preserve the original this context.
  • Must accept any number of arguments and forward them to fn.
  • The timer resets on every new call within the delay window.
closuretimerhigher-order-functionperformancelodash

Important

Interview Tip

Start with the simple version (clearTimeout + setTimeout). Then offer the production version with cancel() and flush(). Distinguish debounce (delay until quiet) from throttle (at most once per interval). Common use cases: search input (debounce), scroll handler (throttle).

Approach: Brute Force

The most direct implementation: store a timer ID, cancel it on each call, reschedule. No extra features — just the core mechanic. This is what most interviews expect first.

Complexity

Time: O(1)Space: O(1)

Pros

  • Simple to understand and explain
  • Covers the core requirement
  • Easy to memorise

Cons

  • No cancel / flush helpers
  • No leading-edge support