Promise-based delay that rejects when an AbortSignal fires
A search box waits a moment before showing a “Still searching…” hint, and a retry loop waits between attempts. Both waits must stop the moment the user leaves the page, otherwise the code wakes up later and updates a screen that no longer exists. The standard way to cancel async work in the browser is an AbortSignal.
Implement delay(ms, options). It returns a promise that resolves after ms milliseconds, unless its signal aborts first.
delay(ms, { signal?, value? }?) // => Promise
setTimeout to wait. A ms that is negative or not a number is treated as 0.options.value (or undefined if no value is given).options.signal is already aborted, return a promise that rejects with signal.reason. Do not start a timer.signal.reason right away and cancel the timer with clearTimeout.signal.addEventListener('abort', ...) and remove the listener when the delay resolves, so long-lived signals do not pile up listeners. An abort after the delay has resolved has no effect.await delay(300); // resolves with undefined after about 300ms
await delay(50, { value: 'ready' }); // => 'ready'
const controller = new AbortController();
const hint = delay(1000, { signal: controller.signal });
controller.abort();
await hint; // rejects with controller.signal.reason (a DOMException named 'AbortError')
const leave = new AbortController();
leave.abort('route changed');
await delay(10, { signal: leave.signal }); // rejects with 'route changed', no timer was started
The tests replace setTimeout and clearTimeout with a fake clock, so call the global functions (not ones you saved earlier) and do not rely on Date.now().