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
delayms, the previous pending invocation is cancelled (its promise rejects with"Debounced"). - After
delayms 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)
- Store the timeout ID and the reject function of the pending promise.
- On each call, clear the previous timeout and reject the previous promise.
- Create a new Promise and set a fresh timeout.
- When the timeout fires, call fn and resolve with its result.
- Reject cancelled calls with "Debounced".
Topics
- Promises & Async
Asked at
Google · Meta · Airbnb
