A Pen by Craig Palermo on CodePen.
Last active
September 23, 2016 00:21
-
-
Save craigpalermo/5fa2f1b4e9bfc728a5ca49cdc220f4b1 to your computer and use it in GitHub Desktop.
Exponential Backoff
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
div#output |
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
/** | |
* 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); |
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
<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