-
-
Save cybersholt/6b93e478fc5345abe2adb01af2f5504a to your computer and use it in GitHub Desktop.
jQuery AJAX smart retry
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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