Last active
January 12, 2022 14:55
-
-
Save yairEO/3f0a5c2d6adbdad14c3c7825abeaab7e to your computer and use it in GitHub Desktop.
jQuery AJAX smart retry
This file contains hidden or 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