2020-05-08 21:15:47 +03:00
|
|
|
import { useEffect, useRef } from 'react'
|
|
|
|
|
2020-07-07 04:26:38 +03:00
|
|
|
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() {
|
2020-05-20 22:39:28 +03:00
|
|
|
const current = savedCallback.current
|
|
|
|
current && current()
|
2020-05-08 21:15:47 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
if (delay !== null) {
|
2020-07-07 04:26:38 +03:00
|
|
|
if (leading) tick()
|
2020-05-08 21:50:27 +03:00
|
|
|
const id = setInterval(tick, delay)
|
2020-05-08 21:15:47 +03:00
|
|
|
return () => clearInterval(id)
|
|
|
|
}
|
2020-08-27 20:05:09 +03:00
|
|
|
return undefined
|
2020-07-07 04:31:08 +03:00
|
|
|
}, [delay, leading])
|
2020-05-08 21:50:27 +03:00
|
|
|
}
|