Implement Debounce with Immediate & Cancel Support
Problem Statement
Implement a `debounce(fn, delay, options)` function that delays invoking `fn` until after `delay` milliseconds have elapsed since the last time the debounced function was invoked. It must preserve `this` and arguments, and provide a `.cancel()` method.
Target Complexity
Time:
O(1) per call
Space:
O(1) closure state
Interview Talking Points:
- • Explain why preserving `this` via `fn.apply(this, args)` is necessary when passing debounced methods to object instances.
- • Discuss `.cancel()` method importance on React component unmount to prevent memory leaks and setState warnings.
Solution Editor (JavaScript)
Ready to run
Test Results
Executes only once after burst of calls
Test #1Supports .cancel() method
Test #2