Exponential Back Off
by pajtai
HTML
<pre id="result"></pre>
JavaScript
console.log = consoleLog;
exponentialBackoff(sometimesFails, 10, 100, function(result) {
console.log('the result is',result);
});
// A function that keeps trying, "toTry" until it returns true or has
// tried "max" number of times. First retry has a delay of "delay".
// "callback" is called upon success.
function exponentialBackoff(toTry, max, delay, callback) {
console.log('max',max,'next delay',delay);
var result = toTry();
if (result) {
callback(result);
} else {
if (max > 0) {
setTimeout(function() {
exponentialBackoff(toTry, --max, delay * 2, callback);
}, delay);
} else {
console.log('we give up');
}
}
}
function sometimesFails() {
var percentFail = 0.8;
return Math.random() >= 0.8;
}
function consoleLog() {
var args = [].slice.apply(arguments);
document.querySelector('#result').innerHTML += '\n' + args.join(' - ');
}