Created
October 14, 2020 20:01
-
-
Save wryk/721e6835b558fe56d9a7d2f4fd5ce910 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
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