Skip to content

Instantly share code, notes, and snippets.

@tomasreichmann
Created November 5, 2018 15:12
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 tomasreichmann/b1d81840b645b5a87ea8dfa69822c3d8 to your computer and use it in GitHub Desktop.
Save tomasreichmann/b1d81840b645b5a87ea8dfa69822c3d8 to your computer and use it in GitHub Desktop.
// retries async check() untill it resolves or time runs out
const retry = async (check = async () => true, timeout = 1000, interval = 100, started = Date.now()) => {
const startTime = Date.now();
return check().catch(
(error) => {
return new Promise((resolve, reject) => {
const resolveTime = Date.now();
if (Date.now() + interval > started + timeout) {
reject(error);
}
setTimeout(
() => retry(check, timeout, interval, started).then(resolve, reject),
Math.max((startTime - resolveTime) + interval, 0)
);
});
}
);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment