Skip to content

Instantly share code, notes, and snippets.

@oleg-koval
Last active April 15, 2019 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save oleg-koval/75494a2f19bc240d7b04ed2596d738bd to your computer and use it in GitHub Desktop.
Save oleg-koval/75494a2f19bc240d7b04ed2596d738bd to your computer and use it in GitHub Desktop.
exponentialBackoff function

A function that keeps trying, "fn" until it returns true or has tried "max" number of times. First retry has a delay of "delay". "callback" is called upon success.

exponentialBackoff(fnFailsSomeTimes, 10, 100, function(result) {
console.log("the result is", result);
});
function exponentialBackoff(fn, max, delay, callback) {
const result = fn();
if (result) {
callback(result);
} else {
if (max > 0) {
setTimeout(function() {
exponentialBackoff(fn, --max, delay * 2, callback);
}, delay);
} else {
console.log("Retry count exceeded. Stopping calls");
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment