call(back)
FrontendmediumSign in to star problems

Debounce with Cancel and Flush

Write a trailing-edge debounce whose returned function also has two controls:

debounceWithControls(fn, wait)  // trailing-edge debounce
  .cancel()                     // drop the pending call
  .flush()                      // run the pending call now (no-op if nothing is pending)

The grader replays timed call scripts on a virtual clock — setTimeout, clearTimeout, and Date.now are stubbed — so build on those, not on performance.now or promises. Each case's input is the wait and a script of [ms, action, ...args] steps; the expected output lists every fire as {at, args}.

Rules

  • The wrapper fires once per burst, wait ms after the last call, with that call's arguments.
  • flush runs the pending call immediately and clears the timer; cancel drops it. Later calls start a fresh cycle either way.
  • Return a real function, not an arrow, so a caller's this is forwarded.

Hints

Hint 1

A closure over one timer id is all a plain debounce needs; each call clears and re-arms it. For cancel and flush, also remember the pending args and this so flush can invoke them.

Hint 2

flush acts only while a timer is pending: clear it and invoke the saved call. cancel clears the timer and forgets the saved call, so the next call starts fresh.

Asked at