Skip to content

Instantly share code, notes, and snippets.

@craigpalermo
Last active September 23, 2016 00:21
Show Gist options
  • Save craigpalermo/5fa2f1b4e9bfc728a5ca49cdc220f4b1 to your computer and use it in GitHub Desktop.
Save craigpalermo/5fa2f1b4e9bfc728a5ca49cdc220f4b1 to your computer and use it in GitHub Desktop.
Exponential Backoff
/**
* Exponential backoff function that will continue to execute the given
* function until either callback returns true or the max number of
* retries is reached.
*
* Source: http://docs.aws.amazon.com/general/latest/gr/api-retries.html
*
* @params {Number} maxRetries
* @params {Function} callback
* @params {Number} curRetries
*/
const exponentialBackoff = function exponentialBackoff(maxRetries, callback, curRetries = 0) {
const wait = Math.pow(2, curRetries) * 100;
const result = callback();
if (curRetries < maxRetries) {
setTimeout(() => {
if (result) {
// Action succeeded
console.log(`Success after ${curRetries} retries`);
} else {
// Action failed, so retry
console.log(`Trying again in ${wait / 1000} seconds`);
exponentialBackoff(maxRetries, callback, curRetries + 1);
}
}, wait);
} else {
// Max number of retries reached, so give up
console.log(`No longer retrying after ${curRetries} attempts`);
}
};
// Test
const alwaysFalse = () => false;
exponentialBackoff(10, alwaysFalse);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment