Loading...
Developer script generator, SQL query synthesis, and automated code review.
export interface RetryOptions {
maxRetries?: number;
baseDelayMs?: number;
maxDelayMs?: number;
factor?: number;
jitter?: boolean;
}
/**
* Execute an asynchronous operation with exponential backoff and jitter.
*/
export async function retryWithBackoff<T>(
fn: () => Promise<T>,
options: RetryOptions = {}
): Promise<T> {
const {
maxRetries = 3,
baseDelayMs = 250,
maxDelayMs = 5000,
factor = 2,
jitter = true,
} = options;
let attempt = 0;
while (true) {
try {
return await fn();
} catch (error) {
attempt++;
if (attempt > maxRetries) {
throw error;
}
const backoff = Math.min(maxDelayMs, baseDelayMs * Math.pow(factor, attempt - 1));
const delay = jitter ? backoff * (0.5 + Math.random() * 0.5) : backoff;
await new Promise((resolve) => setTimeout(resolve, delay));
}
}
}