Last active
September 22, 2019 11:10
-
-
Save intrnl/51d48112e4293593142b23b13f1dd7be 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
import { useEffect, useRef } from 'preact/hooks' | |
/** | |
* @param {function} callback | |
* @param {number} delay | |
*/ | |
function useAwaitInterval (callback, delay) { | |
const cb = useRef() | |
useEffect(() => { | |
cb.current = callback | |
}, [callback]) | |
useEffect(() => { | |
let interval | |
let cancel = false | |
const tick = async () => { | |
if (typeof cb.current === 'function') | |
await cb.current() | |
if (cancel) return | |
interval = setTimeout(tick, delay) | |
} | |
if (typeof delay === 'number') { | |
interval = setTimeout(tick, delay) | |
return () => { | |
clearTimeout(interval) | |
cancel = true | |
} | |
} | |
}, [delay]) | |
} | |
export default useAwaitInterval |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment