uniswap-interface-uncensored/src/hooks/useInterval.ts

26 lines
626 B
TypeScript
Raw Normal View History

2020-05-08 21:15:47 +03:00
import { useEffect, useRef } from 'react'
export default function useInterval(callback: () => void, delay: null | number, leading = true) {
2020-05-08 21:15:47 +03:00
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()
2020-05-08 21:15:47 +03:00
}
if (delay !== null) {
if (leading) tick()
const id = setInterval(tick, delay)
2020-05-08 21:15:47 +03:00
return () => clearInterval(id)
}
return undefined
2020-07-07 04:31:08 +03:00
}, [delay, leading])
}