CodShot
TypeScript Public

Abortable Fetch with Timeout

Cancel a slow fetch request with AbortController while preserving the caller signal.

#typescript #fetch #abortcontroller #error-handling
TypeScript
type FetchWithTimeoutOptions = RequestInit & {
  timeoutMs?: number;
};

export async function fetchWithTimeout(
  input: RequestInfo | URL,
  options: FetchWithTimeoutOptions = {},
): Promise<Response> {
  const {
    timeoutMs = 8000,
    signal: callerSignal,
    ...requestOptions
  } = options;

  const timeoutController = new AbortController();
  const timeoutId = window.setTimeout(() => {
    timeoutController.abort(
      new DOMException('Request timed out.', 'TimeoutError'),
    );
  }, timeoutMs);

  const signal = callerSignal
    ? AbortSignal.any([
        callerSignal,
        timeoutController.signal,
      ])
    : timeoutController.signal;

  try {
    return await fetch(input, {
      ...requestOptions,
      signal,
    });
  } finally {
    window.clearTimeout(timeoutId);
  }
}

Snippet actions

CodShot user
CodShot user
Updated: 2026-08-06 18:36
Public snippets
0
Forks
CodShot AI Help
Ask about CodShot features, plans, workspace, AI limits, referrals, and public help topics.
Hi! I can help you understand how CodShot works. What would you like to know?
For account-specific or sensitive issues, please open a support ticket. Open support