Retry with Exponential Backoff

Retries a function with exponential backoff. Useful for API calls, database operations, or any operation that might fail temporarily.

JavaScript7/16/2025
#utilities#async#error-handling
JavaScript
async function retry(fn, maxAttempts = 3, baseDelay = 1000) {
  let attempts = 0;
  
  while (attempts < maxAttempts) {
    try {
      return await fn();
    } catch (error) {
      attempts++;
      if (attempts >= maxAttempts) throw error;
      
      const delay = baseDelay * Math.pow(2, attempts - 1);
      await new Promise(resolve => setTimeout(resolve, delay));
    }
  }
}
...
Loading comments...