Created
March 29, 2017 02:10
-
-
Save davidraedev/7970d63ed6fec3cca3d0b58e85da2bbd to your computer and use it in GitHub Desktop.
simple javascript ajax with exponential backoff (untested)
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
var timeout = { | |
initial: 10, // start backoff | |
backoff: 1.5, // backoff exponent | |
max: 5000, // maximum retry backoff | |
fail: ( 1000 * 60 * 3 ), // stop retrying after this time | |
loop: 0, // current number of tries | |
}; | |
function getUrl( url ) { | |
if ( ! timeout.start ) | |
timeout.start = +new Date(); | |
$.ajax({ | |
method: "GET", | |
url: data_url, | |
success: function( response ) { | |
}, | |
error: function( error ){ | |
if ( ( +new Date - timeout.start ) > timeout.fail ) | |
return handleGetUrlError( error ); | |
var timeout = Math.min( Math.pow( ( ++timeout.loop * initial ), 2 ), timeout.max ); | |
setTimeout( function() { | |
getUrl( url ); | |
}, timeout ); | |
} | |
}); | |
} | |
function handleGetUrlError( error ) { | |
console.error( error ) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment