Skip to content

Instantly share code, notes, and snippets.

@casschin
Created November 19, 2020 04:28
Show Gist options
  • Save casschin/c49fad36df21c602b14f1444ab3292bd to your computer and use it in GitHub Desktop.
Save casschin/c49fad36df21c602b14f1444ab3292bd to your computer and use it in GitHub Desktop.
polling function with the ability to cancel
function poll({ fn, validate, interval = 1000, maxAttempts = 100 }) {
let attempts = 0;
let stop = false;
async function execute(resolve, reject) {
const res = await fn();
attempts += 1;
if (validate(res)) {
resolve(res);
} else if (maxAttempts === attempts) {
return reject("Hit max poll attempts");
} else if (!stop) {
setTimeout(execute, interval, resolve, reject);
}
}
function clear() {
stop = true;
}
return [new Promise(execute), clear];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment