• Performs a network request with a timeout.

    Parameters

    • url: string

      The URL to fetch.

    • options: RequestInit = {}

      Fetch options.

    • timeout: number = 10000

      Timeout in milliseconds (default: 10000).

    Returns Promise<Response>

    A promise that resolves to the fetch Response.

    If the request times out or the response is not ok.

    const response = await fetchWithTimeout('https://api.example.com', {}, 5000);
    
    export async function fetchWithTimeout(
    url: string,
    options: RequestInit = {},
    timeout = 10000,
    ): Promise<Response> {
    const controller = new AbortController();
    const { signal } = controller;

    const timeoutId = setTimeout(() => controller.abort(), timeout);

    try {
    const response = await fetch(url, {
    ...options,
    signal,
    });

    if (!response.ok) {
    throw response;
    }

    return response;
    } catch (error) {
    // AbortError is caused by our timeout
    if (error instanceof Error && error.name === "AbortError") {
    const timeoutError = new Error("Request timed out");
    timeoutError.name = "TimeoutError";
    throw timeoutError;
    }
    throw error;
    } finally {
    clearTimeout(timeoutId);
    }
    }