Error Retry Logic

Implement retry logic for failed operations

IntermediateTopic: Error Handling
Back

JavaScript Error Retry Logic Program

This program helps you to learn the fundamental structure and syntax of JavaScript programming.

Try This Code
// Method 1: Simple retry
async function retryOperation(fn, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await fn();
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            console.log(`Retry ${i + 1} failed, retrying...`);
            await new Promise(resolve => setTimeout(resolve, 1000 * (i + 1)));
        }
    }
}

// Method 2: Retry with exponential backoff
async function retryWithBackoff(fn, maxRetries = 3, baseDelay = 1000) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await fn();
        } catch (error) {
            if (i === maxRetries - 1) throw error;
            const delay = baseDelay * Math.pow(2, i);
            console.log(`Retry ${i + 1} after ${delay}ms`);
            await new Promise(resolve => setTimeout(resolve, delay));
        }
    }
}

// Method 3: Retry with conditions
async function retryWithCondition(fn, shouldRetry, maxRetries = 3) {
    for (let i = 0; i < maxRetries; i++) {
        try {
            return await fn();
        } catch (error) {
            if (!shouldRetry(error) || i === maxRetries - 1) {
                throw error;
            }
            await new Promise(resolve => setTimeout(resolve, 1000));
        }
    }
}

// Usage
retryWithCondition(
    () => fetch('https://api.example.com/data'),
    (error) => error.message.includes('network') || error.message.includes('timeout'),
    3
);

// Method 4: Retry class
class RetryHandler {
    constructor(options = {}) {
        this.maxRetries = options.maxRetries || 3;
        this.delay = options.delay || 1000;
        this.backoff = options.backoff || 'exponential';
    }
    
    async execute(fn) {
        for (let i = 0; i < this.maxRetries; i++) {
            try {
                return await fn();
            } catch (error) {
                if (i === this.maxRetries - 1) throw error;
                
                const delay = this.calculateDelay(i);
                await this.wait(delay);
            }
        }
    }
    
    calculateDelay(attempt) {
        if (this.backoff === 'exponential') {
            return this.delay * Math.pow(2, attempt);
        }
        return this.delay;
    }
    
    wait(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }
}

const retryHandler = new RetryHandler({ maxRetries: 3, delay: 1000 });
retryHandler.execute(() => fetch('https://api.example.com/data'));
Output
Retry 1 failed, retrying...
Retry 2 failed, retrying...
Retry 1 after 1000ms
Retry 2 after 2000ms

Understanding Error Retry Logic

Retry logic handles transient failures.

Simple Retry

Fixed attempts
Fixed delay
Re-throw on failure

Exponential Backoff

Increasing delays
1s, 2s, 4s, etc.
Reduces load

Conditional Retry

Check error type
Retry only certain errors
Skip others

Retry Class

Configurable
Reusable
Flexible

Use Cases

Network requests
Database operations
External APIs
Transient failures

Best Practices

Limit retries
Use backoff
Check error types
Don't retry forever

Let us now understand every line and the components of the above program.

Note: To write and run JavaScript programs, you need to set up the local environment on your computer. Refer to the complete article Setting up JavaScript Development Environment. If you do not want to set up the local environment on your computer, you can also use online IDE to write and run your JavaScript programs.

Practical Learning Notes for Error Retry Logic

This JavaScript program is part of the "Error Handling" topic and is designed to help you build real problem-solving confidence, not just memorize syntax. Start by understanding the goal of the program in plain language, then trace the logic line by line with a custom input of your own. Once you can predict the output before running the code, your understanding becomes much stronger.

A reliable practice pattern is to run the original version first, then modify only one condition or variable at a time. Observe how that single change affects control flow and output. This deliberate style helps you understand loops, conditions, and data movement much faster than copying full solutions repeatedly.

For interview preparation, explain this solution in three layers: the high-level approach, the step-by-step execution, and the time-space tradeoff. If you can teach these three layers clearly, you are ready to solve close variations of this problem under time pressure.

Table of Contents