useInterval
API
import useInterval from '@restart/hooks/useInterval'useInterval(fn: () => void, ms: number) => voidCreates a
setIntervalthat is properly cleaned up when a component unmountedfunction Timer() {const [timer, setTimer] = useState(0)useInterval(() => setTimer(i => i + 1), 1000)return <span>{timer} seconds past</span>}Parameters
fn() => voidan function run on each interval
msnumberThe milliseconds duration of the interval
Return Value void
useInterval(fn: () => void, ms: number, paused: boolean) => voidCreates a pausable
setIntervalthat is properly cleaned up when a component unmountedconst [paused, setPaused] = useState(false)const [timer, setTimer] = useState(0)useInterval(() => setTimer(i => i + 1), 1000, paused)return (<span>{timer} seconds past<button onClick={() => setPaused(p => !p)}>{paused ? 'Play' : 'Pause' }</button></span>)Parameters
fn() => voidan function run on each interval
msnumberThe milliseconds duration of the interval
pausedbooleanWhether or not the interval is currently running
Return Value void
useInterval(fn: () => void, ms: number, paused: boolean, runImmediately: boolean) => voidCreates a pausable
setIntervalthat fires immediately and is properly cleaned up when a component unmountedconst [timer, setTimer] = useState(-1)useInterval(() => setTimer(i => i + 1), 1000, false, true)// will update to 0 on the first effectreturn <span>{timer} seconds past</span>Parameters
fn() => voidan function run on each interval
msnumberThe milliseconds duration of the interval
pausedbooleanWhether or not the interval is currently running
runImmediatelybooleanWhether to run the function immediately on mount or unpause rather than waiting for the first interval to elapse
Return Value void