Race a promise against a timeout. Reject if it takes too long.
export function withTimeout<T>(
promise: Promise<T>,
ms: number,
message = 'Operation timed out'
): Promise<T> {
let timeoutId: ReturnType<typeof setTimeout>;
const timeout = new Promise<never>((_, reject) => {
timeoutId = setTimeout(() => reject(new Error(message)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timeoutId));
}
// await withTimeout(fetch(url), 5000)
Races the promise against a timeout. Rejects with message if ms elapses first. Clears the timer on settle.
Limit fetch or any async operation duration.
await withTimeout(fetch(url), 5000, 'Fetch timed out');