← All Exercises
Debounce with Cancel, Flush, and an Injected Clock
advancedjavascript
Background
Debouncing powers search suggestions, resize handlers, and autosave. Timer-based code is hard to test, so production utilities inject a clock and expose cancel and flush controls.
Problem
Implement createDebounced(fn, wait, clock) that returns a debounced function with cancel() and flush(). A call schedules fn to run after wait milliseconds of silence; cancel discards the pending call and flush runs it immediately. Use the injected clock for all timing.
Input
A JSON object with wait, calls (each with at and arg), optional cancelAt or flushAt, and advanceTo.
Output
A JSON array of invocation records, each containing the clock time at and the forwarded arguments array.
Sample tests
Sample 1
Input: {"wait":100,"calls":[{"at":0,"arg":"a"},{"at":30,"arg":"b"},{"at":60,"arg":"c"}],"advanceTo":200}Expected: [{"at":160,"args":["c"]}]Sample 2
Input: {"wait":100,"calls":[{"at":0,"arg":"a"},{"at":250,"arg":"b"}],"advanceTo":400}Expected: [{"at":100,"args":["a"]},{"at":350,"args":["b"]}]Sample 3
Input: {"wait":100,"calls":[{"at":0,"arg":"a"}],"cancelAt":50,"advanceTo":300}Expected: []
Sample 4
Input: {"wait":100,"calls":[{"at":0,"arg":"a"}],"flushAt":50,"advanceTo":300}Expected: [{"at":50,"args":["a"]}]Your solution
Learning objective
Understand trailing-edge debouncing, timer ownership, cancellation and flushing, and dependency injection for deterministic async tests.