Skip to content

Instantly share code, notes, and snippets.

@gf3
Last active April 4, 2018 02:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gf3/25522ed3f60e389cb01c to your computer and use it in GitHub Desktop.
Save gf3/25522ed3f60e389cb01c to your computer and use it in GitHub Desktop.
Backoff AJAX requests
/**
* @flow
*/
import request from 'lib/request';
type F<T> = (response: T) => bool;
const BACKOFF_MAX = 60; // seconds
const BACKOFF_ATTEMPTS = 60;
function decay(count: number): number {
if (count <= 0) {
return 0;
}
return Math.min(BACKOFF_MAX, count * 1.4);
}
export function backoff<R>(predicate: F<R>, args: Object): { cancel: () => void, promise: Promise<R> } {
let isCancelled = false;
const promise = new Promise((resolve, reject) => {
let attempts = 0;
let backoffValue = 1;
function run() {
attempts += 1;
request(args).then(response => {
if (predicate(response)) {
return resolve(response);
}
else if (isCancelled == true) {
return reject({ isCancelled });
}
reRun();
}, error => {
if (attempts === BACKOFF_ATTEMPTS) {
return reject(error);
}
else if (isCancelled == true) {
return reject({ isCancelled });
}
reRun();
});
}
function reRun() {
backoffValue = decay(backoffValue);
setTimeout(run, backoffValue * 1000);
}
run();
});
return {
cancel() {
isCancelled = true;
},
promise
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment