Skip to content

Instantly share code, notes, and snippets.

@tatethurston
Created November 14, 2017 19:10
Show Gist options
  • Save tatethurston/372dcfc1b664be45f540e072155514bd to your computer and use it in GitHub Desktop.
Save tatethurston/372dcfc1b664be45f540e072155514bd to your computer and use it in GitHub Desktop.
JavaScript polling
// fn: () => Promise<Boolean>
const poll = (fn, interval = 100, maxWait = 60000) => {
const start = Date.now();
let last = 0;
return new Promise((resolve, reject) => {
const _poll = () => {
const now = Date.now();
console.log(start, last, now, interval);
if (now > start + maxWait) {
reject('Polling maxWait exceeded');
return;
}
if (now > last + interval) {
last = Date.now();
fn()
.then(predicate => predicate ? resolve(predicate) : _poll())
.catch(_poll);
} else {
setTimeout(_poll, last + interval - now);
}
};
_poll();
});
};
@edburns
Copy link

edburns commented Nov 14, 2017

Nice JavaScript

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment