01

Debounce, with cancel

20 min·senior·

You're building a search-as-you-type feature. Implement a debounce function that:

  • Takes a function fn and a delay wait (ms)
  • Returns a debounced version that delays execution until wait ms have passed since the last call
  • The returned function has a .cancel() method to cancel any pending invocation
  • Preserves this context 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:

  1. Time complexity of calling the debounced function
  2. Time complexity of .cancel()
  3. 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