Skip to content

Instantly share code, notes, and snippets.

@cybersholt
Forked from yairEO/jQuery.ajaxRetry.js
Created September 1, 2017 19:03
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 cybersholt/6b93e478fc5345abe2adb01af2f5504a to your computer and use it in GitHub Desktop.
Save cybersholt/6b93e478fc5345abe2adb01af2f5504a 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