useInterval

    API

    import useInterval from '@restart/hooks/useInterval'
    • useInterval(fn: () => void, ms: number) => void

      Creates a setInterval that is properly cleaned up when a component unmounted

      function Timer() {
      const [timer, setTimer] = useState(0)
      useInterval(() => setTimer(i => i + 1), 1000)
      return <span>{timer} seconds past</span>
      }

      Parameters

      • fn() => void

        an function run on each interval

      • msnumber

        The milliseconds duration of the interval

      Return Value void

    • useInterval(fn: () => void, ms: number, paused: boolean) => void

      Creates a pausable setInterval that is properly cleaned up when a component unmounted

      const [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() => void

        an function run on each interval

      • msnumber

        The milliseconds duration of the interval

      • pausedboolean

        Whether or not the interval is currently running

      Return Value void

    • useInterval(fn: () => void, ms: number, paused: boolean, runImmediately: boolean) => void

      Creates a pausable setInterval that fires immediately and is properly cleaned up when a component unmounted

      const [timer, setTimer] = useState(-1)
      useInterval(() => setTimer(i => i + 1), 1000, false, true)
      // will update to 0 on the first effect
      return <span>{timer} seconds past</span>

      Parameters

      • fn() => void

        an function run on each interval

      • msnumber

        The milliseconds duration of the interval

      • pausedboolean

        Whether or not the interval is currently running

      • runImmediatelyboolean

        Whether to run the function immediately on mount or unpause rather than waiting for the first interval to elapse

      Return Value void