Skip to content

Instantly share code, notes, and snippets.

@yairEO
Last active January 12, 2022 14:55
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save yairEO/3f0a5c2d6adbdad14c3c7825abeaab7e to your computer and use it in GitHub Desktop.
Save yairEO/3f0a5c2d6adbdad14c3c7825abeaab7e 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