Skip to content

Instantly share code, notes, and snippets.

@intrnl
Last active September 22, 2019 11:10
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 intrnl/51d48112e4293593142b23b13f1dd7be to your computer and use it in GitHub Desktop.
Save intrnl/51d48112e4293593142b23b13f1dd7be to your computer and use it in GitHub Desktop.
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