Skip to content

Instantly share code, notes, and snippets.

@wryk
Created October 14, 2020 20:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wryk/721e6835b558fe56d9a7d2f4fd5ce910 to your computer and use it in GitHub Desktop.
Save wryk/721e6835b558fe56d9a7d2f4fd5ce910 to your computer and use it in GitHub Desktop.
const timeout = (fn, ms) => {
const id = setTimeout(fn, ms)
return () => clearTimeout(id)
}
const interval = (fn, ms) => {
const id = setInterval(fn, ms)
return () => clearInterval(id)
}
const animationFrame = fn => {
const id = requestAnimationFrame(fn)
return () => cancelAnimationFrame(id)
}
const onEvent = (target, name, handler, options) => {
target.addEventListener(name, handler, options)
return () => target.removeEventListener(name, handler, options)
}
const onEventOnce = (target, name, handler, options) => {
const newHandler = e => {
target.removeEventListener(name, newHandler, options)
handler(e)
}
target.addEventListener(name, newHandler, options)
return () => target.removeEventListener(name, newHandler, options)
}
const observeEvent = (target, name, options) => {
return new Observable(observer => {
const unsubscribe = onEvent(target, name, e => observer.next(e), options)
return () => unsubscribe()
})
}
const promiseEvent = (target, name, options) => {
const controller = new AbortController()
const { signal } = controller
const promise = new Promise((resolve, reject) => {
const unsubscribe = onEventOnce(target, name, e => resolve(e), options)
onEventOnce(signal, 'abort', () => {
unsubscribe()
reject(new DOMException('Aborted', 'AbortError'))
})
})
const unsubscribe = () => {
controller.abort()
}
return [promise, unsubscribe]
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment