uniswap-interface-uncensored/src/hooks/useInterval.ts
2020-07-06 21:26:38 -04:00

26 lines
607 B
TypeScript

import { useEffect, useRef } from 'react'
export default function useInterval(callback: () => void, delay: null | number, leading = true) {
const savedCallback = useRef<() => void>()
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback
}, [callback])
// Set up the interval.
useEffect(() => {
function tick() {
const current = savedCallback.current
current && current()
}
if (delay !== null) {
if (leading) tick()
const id = setInterval(tick, delay)
return () => clearInterval(id)
}
return
}, [delay])
}