Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save cicorias/ac7a30002f4070ab9dc7c1064b0ba9ad to your computer and use it in GitHub Desktop.
Save cicorias/ac7a30002f4070ab9dc7c1064b0ba9ad to your computer and use it in GitHub Desktop.
function exponentialBackoff(toTry, max, delay, callback) {
new Promise(function(resolve, reject) {
// do a thing then…
var ret = toTry.toString();
ret = ret.substr('function '.length);
ret = ret.substr(0, ret.indexOf('('));
console.log('EB '+ret+' max',max,'next delay',delay);
var result = toTry();
if (result) {
resolve(true);
} else {
if (max > 0) {
setTimeout(function() {
exponentialBackoff(toTry, --max, delay * 2, callback);
}, delay);
} else {
console.log('and I\'m giving up now...');
resolve(false);
}
}
}).then(function(result){
callback(result);
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment