Skip to content

Instantly share code, notes, and snippets.

@kenoir
Last active September 4, 2023 16:18
Show Gist options
  • Select an option

  • Save kenoir/2ab02be92a34d9ce9da0 to your computer and use it in GitHub Desktop.

Select an option

Save kenoir/2ab02be92a34d9ce9da0 to your computer and use it in GitHub Desktop.
Functional(ish) backoff algorithm
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
Copy link

// BECAUSE PASSING AROUND VALUES IS PRETTY UGLY IN JS
// I OPTED FOR CONSTANTS THAT ARE ACCESSIBLE COMPLETELY WITHIN THIS MODULE
// `const` ISN'T IN ES5 SPEC AND SUPPORT IS POOR: (IE11, Safari 5, Opera 12, Firefox ?, Chrome ?)
var FAILCOUNT = 1;
var THRESHOLD = 5;
var SECONDS_PER_INTERVAL = 5;

function intervalDelay() {
    return (Math.floor(Math.random() * FAILCOUNT) + 1) * (FAILCOUNT + 1);
}

function fuzzDelay(delay) {
    return delay * (Math.random() + 0.5);
}

// THIS WONT WORK AS `callback` ISN'T A FUNCTION!
// ALSO NOT SURE I UNDERSTAND WHAT YOU'RE TRYING TO DO
function failCheck(callback) {
    return FAILCOUNT < THRESHOLD ? callback(FAILCOUNT) : false;
}

// `timeInSeconds` ISN'T A GOOD NAME
// AS IT DOESN'T ALWAYS REPRESENT A NUMBER 
// (SOMETIMES IT'S A BOOLEAN?)    
function timeInSeconds(delay) {
    return delay === false ? false : delay * SECONDS_PER_INTERVAL;
}

// INLINED THE FUNCTIONS
console.log(
    timeInSeconds(
        failCheck(
            fuzzDelay(
                intervalDelay()
            )
        )
    )
);

@kenoir
Copy link
Author

kenoir commented Jul 8, 2014

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment