useInterval
API
import useInterval from '@restart/hooks/useInterval'
useInterval
(fn: () => void, ms: number) => voidCreates a
setInterval
that 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
ms
numberThe milliseconds duration of the interval
Return Value void
useInterval
(fn: () => void, ms: number, paused: boolean) => voidCreates a pausable
setInterval
that 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
ms
numberThe milliseconds duration of the interval
paused
booleanWhether or not the interval is currently running
Return Value void
useInterval
(fn: () => void, ms: number, paused: boolean, runImmediately: boolean) => voidCreates a pausable
setInterval
that 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
ms
numberThe milliseconds duration of the interval
paused
booleanWhether or not the interval is currently running
runImmediately
booleanWhether to run the function immediately on mount or unpause rather than waiting for the first interval to elapse
Return Value void