Created
March 21, 2020 22:55
-
-
Save mikehwagz/db89246515778f90c4943645780b46e9 to your computer and use it in GitHub Desktop.
This file contains 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
export function poll(delay, cb, first = true) { | |
let lastCb = Promise.resolve() | |
let timeoutId = null | |
let off = false | |
if (first) { | |
handleCallback() | |
} else { | |
done() | |
} | |
function done() { | |
if (off) return | |
timeoutId = setTimeout(handleCallback, delay) | |
} | |
function handleCallback() { | |
lastCb = cb(done) | |
} | |
return () => { | |
clearTimeout(timeoutId) | |
off = true | |
return lastCb || Promise.resolve() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment