Skip to content

Instantly share code, notes, and snippets.

@mikehwagz
Created March 21, 2020 22:55
Show Gist options
  • Save mikehwagz/db89246515778f90c4943645780b46e9 to your computer and use it in GitHub Desktop.
Save mikehwagz/db89246515778f90c4943645780b46e9 to your computer and use it in GitHub Desktop.
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