Skip to content

Instantly share code, notes, and snippets.

@advait
Created August 21, 2014 19:44
Show Gist options
  • Save advait/7665d91c5d4b0e3cf632 to your computer and use it in GitHub Desktop.
Save advait/7665d91c5d4b0e3cf632 to your computer and use it in GitHub Desktop.
Fibonacci backoff for promises. Retries a function indefinitely until it succeeds (Promise resolves).
/**
* Given a function promiseFunctionToRetry that returns a Promise, repeatedly
* call the function with a fibonacci backoff until it results in a resolved
* Promise.
* @param {function} promiseFunctionToRetry a function that returns a Promise
* that can potentially reject. This may be called multiple times.
* @param {number?} backoff An optional starting backoff in ms (default 1000)
* @return {Promise} guaranteed to never reject
*/
var backoff = function(promiseFunctionToRetry, backoff) {
return new Promise(function(resolve) {
var currentBackoff = backoff || 1000;
var backoffStep = currentBackoff;
var retry = function() {
promiseFunctionToRetry()
.then(resolve, function() {
setTimeout(retry, currentBackoff);
var temp = currentBackoff;
currentBackoff += backoffStep;
backoffStep = temp;
});
};
retry();
});
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment