Last active
September 4, 2023 16:18
-
-
Save kenoir/2ab02be92a34d9ce9da0 to your computer and use it in GitHub Desktop.
Functional(ish) backoff algorithm
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
| var failCount = 6; | |
| // These can be constants | |
| var FAIL_THRESHOLD = 5; | |
| var SECONDS_PER_INTERVAL = 5; | |
| var FUZZ_FACTOR = 0.1; | |
| // Returns delay 'fuzzed' by a random amount | |
| function fuzzDelay(delay) { | |
| var initial = function(delay) { return (delay - ((delay * FUZZ_FACTOR) / 2)); }; | |
| var fuzziness = function(delay) { return (Math.random() * delay * FUZZ_FACTOR); }; | |
| return initial(delay) + fuzziness(delay); | |
| } | |
| // Returns the number of delay intervals to wait | |
| function delayInterval(failCount) { | |
| var intervals = function(failCount) { return (Math.floor(Math.random() * failCount) + 1); }; | |
| var multiplier = function(failCount) { return (failCount + 1); }; | |
| return intervals(failCount) * multiplier(failCount); | |
| } | |
| // Determines whether to call through given the current number of failures | |
| function continuePolling(failCount, threshold, callback) { | |
| return (failCount < threshold) ? callback(failCount) : -1; | |
| } | |
| // Returns the wait time in seconds | |
| function timeInSeconds(failCount) { | |
| return continuePolling(failCount, FAIL_THRESHOLD, function(){ | |
| return fuzzDelay(delayInterval(failCount)); | |
| }) * SECONDS_PER_INTERVAL; | |
| } | |
| // rather unsatisfactorily this returns a negative number as an indication that | |
| // the failure threshold has been exceeded | |
| console.log(timeInSeconds(failCount)); |
Integralist
commented
Jul 8, 2014
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment