Retry Logic
Build retry functionality with Deferreds — attempt the operation, and on failure, try again after a delay up to a maximum number of attempts.
Build retry functionality with Deferreds — attempt the operation, and on failure, try again after a delay up to a maximum number of attempts.
function retryRequest(url, attempts, delay) {
const dfd = $.Deferred();
function attempt(n) {
$.getJSON(url)
.done(data => dfd.resolve(data))
.fail(function() {
if (n > 0) {
setTimeout(() => attempt(n - 1), delay);
} else {
dfd.reject("Max retries exceeded");
}
});
}
attempt(attempts);
return dfd.promise();
}
retryRequest("/api/data", 3, 1000)
.done(data => render(data))
.fail(err => showError(err));
Use exponential backoff: delay * Math.pow(2, attempt) for production retry logic.