Skip to content

Instantly share code, notes, and snippets.

@tatethurston
Created June 28, 2017 18:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tatethurston/f16003fb6c2d3934621e982d39865bd5 to your computer and use it in GitHub Desktop.
Save tatethurston/f16003fb6c2d3934621e982d39865bd5 to your computer and use it in GitHub Desktop.
Retry jQuery AJAX requests with exponential backoff
import $ from 'jquery';
import uuidv4 from 'uuid/v4';
const wait = ms => $.Deferred(defer => setTimeout(defer.resolve, ms));
const request = (opts, numTries = 0) => {
/*
* Retry failed requests 2 additional times with exponential backoff
*/
const RETRY_COUNT = 2;
const INITIAL_NETWORK_RETRY_DELAY = 500;
const delay = INITIAL_NETWORK_RETRY_DELAY + (INITIAL_NETWORK_RETRY_DELAY * numTries);
let idempotencyKey;
if (opts.type === 'POST' && !opts.idempotencyKey) {
idempotencyKey = uuidv4();
}
const options = Object.assign({idempotencyKey}, opts)
const $d = $.ajax(options);
return $d.then(null, (xhr) => {
if (xhr.readyState < 4 && numTries < RETRY_COUNT) {
return wait(delay).then(() => request(options, numTries + 1));
}
return $d;
});
};
@robinc2402
Copy link

Thanks for sharing. 🤝

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment