Skip to content

Instantly share code, notes, and snippets.

@korrio
Created May 16, 2023 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save korrio/eb5dd101ea9249982de68708e5a65077 to your computer and use it in GitHub Desktop.
Save korrio/eb5dd101ea9249982de68708e5a65077 to your computer and use it in GitHub Desktop.
useInterval.ts
import { useEffect, useRef } from 'react'
export const useInterval = (
callback: () => Promise<void>,
delay: number | null | false
) => {
const savedCallback = useRef<() => Promise<void>>()
useEffect(() => {
savedCallback.current = callback
}, [callback])
useEffect(() => {
const tick = () => {
savedCallback?.current()
}
if (delay) {
const id = setInterval(tick, delay)
return () => {
clearInterval(id)
}
}
}, [callback, delay])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment