Type of the function result
Async function to execute
Retry and timeout configuration
Maximum number of retry attempts after the initial call
OptionalmaxDelayMs?: numberMaximum delay cap in milliseconds (default: 30000); prevents unbounded backoff growth
OptionalretryDelayMs?: numberBase delay between retry attempts in milliseconds (default: 1000)
OptionalshouldRetry?: (error: unknown) => booleanPredicate that decides if a failed attempt should be retried (default: retry all non-timeout errors)
OptionaltimeoutErrorMessage?: stringCustom error message for timeout errors
OptionaltimeoutMs?: numberOptional per-attempt timeout in milliseconds (omit if fn handles timeout internally)
Promise that resolves with the result
// Retry up to 3 times (4 total attempts) on 5xx errors only with timeout
const data = await withRetry(
() => fetchFromAPI('/endpoint'),
{
maxRetries: 3,
timeoutMs: 5000,
retryDelayMs: 1000,
shouldRetry: (error) => error.statusCode >= 500
}
);
// Retry without additional timeout (fn handles timeout internally)
const data2 = await withRetry(
() => withTimeoutAndAbort(signal => fetch(url, { signal }), 5000),
{
maxRetries: 3,
retryDelayMs: 1000,
shouldRetry: (error) => error.statusCode >= 500
}
);
Execute a function with retry logic and timeout
Retries the operation up to options.maxRetries times (for a total of maxRetries + 1 attempts including the initial call). Each retry has its own timeout (if timeoutMs is provided).
By default, all non-TimeoutError failures are considered retryable. To restrict retries to transient failures only (for example, network errors or 5xx status codes), provide a options.shouldRetry predicate that returns true only for errors that should be retried.