Created
November 14, 2017 19:10
-
-
Save tatethurston/372dcfc1b664be45f540e072155514bd to your computer and use it in GitHub Desktop.
JavaScript polling
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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(); | |
}); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Nice JavaScript