Skip to content

Instantly share code, notes, and snippets.

@shopglobal
Forked from yairEO/jQuery.ajaxRetry.js
Created September 22, 2017 22:53
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 shopglobal/6ecaa3167bc912f549d44d7990a74855 to your computer and use it in GitHub Desktop.
Save shopglobal/6ecaa3167bc912f549d44d7990a74855 to your computer and use it in GitHub Desktop.
jQuery AJAX smart retry
// enhance the original "$.ajax" with a retry mechanism
$.ajax = (($oldAjax) => {
// on fail, retry by creating a new Ajax deferred
function check(a,b,c){
var shouldRetry = b != 'success' && b != 'parsererror';
if( shouldRetry && --this.retries > 0 )
setTimeout(() => { $.ajax(this) }, this.retryInterval || 100);
}
return settings => $oldAjax(settings).always(check)
})($.ajax);
// USAGE:
// now we can use the "retries" property if we need to retry on fail
$.ajax({
type : 'GET',
url : 'http://www.whatever123.gov',
timeout : 2000,
retries : 3, // <-------- Optional
retryInterval : 2000 // <-------- Optional
})
// Problem: "fail" will only be called once, and not for each retry
.fail(console.warn);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment