Retry Mechanism - Problem
Implement a retry wrapper function that attempts to execute an operation up to N times before giving up. The function should handle failures gracefully and include a delay between retry attempts.
Your function should:
- Accept an operation function, maximum retry count, and delay duration
- Execute the operation and return its result if successful
- If the operation fails, wait for the specified delay and try again
- After
Nfailed attempts, throw or return an error indicating failure
The operation function will randomly succeed or fail to simulate real-world scenarios.
Input & Output
Example 1 — Basic Retry with Success
$
Input:
maxRetries = 3, delayMs = 500
›
Output:
Success on attempt 2
💡 Note:
First attempt fails, wait 500ms, second attempt succeeds and returns success message
Example 2 — All Attempts Fail
$
Input:
maxRetries = 2, delayMs = 1000
›
Output:
Failed after 2 attempts
💡 Note:
Both attempts fail despite waiting 1000ms between them, return failure message
Example 3 — Immediate Success
$
Input:
maxRetries = 5, delayMs = 200
›
Output:
Success on attempt 1
💡 Note:
First attempt succeeds immediately, no delay needed
Constraints
- 1 ≤ maxRetries ≤ 10
- 10 ≤ delayMs ≤ 5000
- Operation has random 60% success rate
Visualization
Tap to expand
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code