TypeScript

Promise with Timeout

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Race a promise against a timeout — if the work takes longer than `ms`, reject with a timeout error. Cancels nothing on its own (use AbortController for that), but unblocks the caller.
TypeScript
Raw
export function withTimeout<T>(p: Promise<T>, ms: number, label = 'operation'): Promise<T> {
  let timer: ReturnType<typeof setTimeout>;
  const timeout = new Promise<never>((_, reject) => {
    timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
  });
  return Promise.race([p, timeout]).finally(() => clearTimeout(timer));
}

// Usage
try {
  const data = await withTimeout(fetch('/slow-api').then(r => r.json()), 5_000, 'fetch /slow-api');
} catch (e) {
  console.error(e);   // either fetch error OR "fetch /slow-api timed out after 5000ms"
}
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.