Debounce, with cancel
20 min·senior·closures · this-binding · timers
You're building a search-as-you-type feature. Implement a debounce function that:
- Takes a function
fnand a delaywait(ms) - Returns a debounced version that delays execution until
waitms have passed since the last call - The returned function has a
.cancel()method to cancel any pending invocation - Preserves
thiscontext and forwards arguments
const search = debounce((q) => fetchResults(q), 300); search('hel'); search('hello'); // cancels the previous pending call // 300ms later, fetchResults('hello') runs search.cancel(); // cancels any pending call
After implementing, analyze:
- Time complexity of calling the debounced function
- Time complexity of
.cancel() - Space complexity of the factory
expected time · O(1) per call
expected space · O(1) per debounced fn
4 lines
⏵ run · no run yet · ctrl+enter