You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
39 lines
831 B
39 lines
831 B
import { useEffect, useRef } from 'react'
|
|
|
|
import noop from 'lodash/noop'
|
|
|
|
import { useToggle } from 'hooks'
|
|
|
|
type Args = {
|
|
callback: () => void,
|
|
intervalDuration: number,
|
|
startImmediate?: boolean,
|
|
}
|
|
|
|
export const useInterval = ({
|
|
callback = noop,
|
|
intervalDuration,
|
|
startImmediate = true,
|
|
}: Args) => {
|
|
const {
|
|
close: stop,
|
|
isOpen: isRunning,
|
|
open: start,
|
|
} = useToggle(startImmediate)
|
|
const savedCallback = useRef(callback)
|
|
|
|
useEffect(() => {
|
|
savedCallback.current = callback
|
|
}, [callback])
|
|
|
|
useEffect(() => {
|
|
if (!isRunning) return undefined
|
|
|
|
if (startImmediate) savedCallback.current()
|
|
|
|
const id = setInterval(savedCallback.current, intervalDuration)
|
|
return () => clearInterval(id)
|
|
}, [isRunning, intervalDuration, callback, startImmediate])
|
|
|
|
return { start, stop }
|
|
}
|
|
|