SyntaxStudy
Sign Up
jQuery Retry Logic with Deferred
jQuery Advanced 5 min read

Retry Logic with Deferred

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.

Example
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));
Pro Tip

Use exponential backoff: delay * Math.pow(2, attempt) for production retry logic.