Async Debounce

MediumPromises & Async20 min4 tests

Implement debounceAsync(fn, delay) that debounces an async function.

Requirements

  • Returns a debounced function that returns a Promise.
  • If called again before delay ms, the previous pending invocation is cancelled (its promise rejects with "Debounced").
  • After delay ms of inactivity, the function is called and the promise resolves with its result.

Example

const debouncedFetch = debounceAsync(async (q) => 'result: ' + q, 100);
const p1 = debouncedFetch('a'); // will be cancelled
const p2 = debouncedFetch('b'); // will execute after 100ms
// p1 rejects with "Debounced", p2 resolves with "result: b"
Hints (5)
  1. Store the timeout ID and the reject function of the pending promise.
  2. On each call, clear the previous timeout and reject the previous promise.
  3. Create a new Promise and set a fresh timeout.
  4. When the timeout fires, call fn and resolve with its result.
  5. Reject cancelled calls with "Debounced".

Topics

  • Promises & Async

Asked at

Google · Meta · Airbnb

Join Us
blur