FrontendInterviews.dev

Loading problem…

87. Advanced Debounce Function

Medium•
Acceptance: 100.00%
•
🔓3/3 Pro unlocks today

This problem builds on debounce-function. Complete that first, then load your solution to continue.

Implement an advanced debounce with cancellation, flushing, and optional immediate mode.

Requirements

1) Signature

  • Implement debounce(fn, delay, immediate = false).
  • Return a debounced function debounced(...args) with methods:
  • debounced.cancel()
  • debounced.flush()

2) Trailing mode (immediate = false)

  • Calls reset the timer.
  • Only the latest call in a burst is eventually invoked.
  • debounced returns undefined while work is pending.
  • flush() immediately executes the pending call and returns its result.

3) Immediate mode (immediate = true)

  • First call in an idle window executes immediately and returns result.
  • Calls during the delay window do not execute fn; they only extend the cooldown timer.
  • No trailing invocation occurs from those suppressed calls.

4) Utility behavior

  • cancel() clears any pending timer and pending invocation state.
  • flush() returns undefined when nothing is pending (or when in immediate mode).
  • Preserve call-site this and latest arguments when invoking fn.

5) Delay edge case

  • With delay = 0, execution must remain asynchronous in trailing mode.

Examples

const d = debounce((x) => x * 2, 50)
d(1)
d(2)
d(3)
// after ~50ms => fn runs once with 3
const d = debounce((x) => x + 1, 100)
d(4)
d.flush() // 5 (runs immediately)
const d = debounce((x) => x, 100, true)
d("a") // "a" (immediate)
d("b") // undefined (suppressed)

Constraints

  • Expose cancel() and flush() on the returned debounced function.
  • In trailing mode, only latest call in a burst may execute.
  • In immediate mode, execute only first idle-window call and suppress rest until cooldown ends.
  • Preserve this and arguments on actual invocation.
  • flush() executes pending trailing work immediately or returns undefined if none.