10LOC

#fetch

Web Platformintermediate

AbortSignal.any() to combine multiple abort signals into one

const routeChangeController = new AbortController();
window.addEventListener("pagehide", () => routeChangeController.abort(), { once: true });

export const search = (query: string) => {
  const requestController = new AbortController();

Cancel a fetch when any of several unrelated conditions fires — a timeout, a route change, an explicit cancel — without hand-rolling a signal merger.

Node.jsintermediate

AbortController to cancel a fetch cleanly after a timeout

export const fetchWithTimeout = async (url: string, timeoutMs: number) => {
  const signal = AbortSignal.timeout(timeoutMs);
  try {
    const response = await fetch(url, { signal });
    return await response.text();

Use AbortSignal.timeout() to cancel a fetch after N milliseconds and tell a timeout apart from every other kind of failure.