Skip to content

Instantly share code, notes, and snippets.

@pablospaniard
Created May 14, 2019 16:04
Show Gist options
  • Select an option

  • Save pablospaniard/00f4e7fd538fefd6d36b3643b2914cc3 to your computer and use it in GitHub Desktop.

Select an option

Save pablospaniard/00f4e7fd538fefd6d36b3643b2914cc3 to your computer and use it in GitHub Desktop.
/* eslint-disable consistent-return */
import { useEffect, useRef } from 'react'
export default function useInterval(callback, delay, running = false) {
const savedCallback = useRef()
// Remember the latest callback.
useEffect(() => {
savedCallback.current = callback
}, [callback])
// Set up the interval.
useEffect(() => {
function tick() {
savedCallback.current()
}
if (running && delay !== null) {
const id = setInterval(tick, delay)
return () => clearInterval(id)
}
}, [delay, running])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment