Skip to content

Instantly share code, notes, and snippets.

@jacob-lcs
Created May 2, 2022 09:55
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 jacob-lcs/0c91e387a22a2a09a72b16f7d8ac9e74 to your computer and use it in GitHub Desktop.
Save jacob-lcs/0c91e387a22a2a09a72b16f7d8ac9e74 to your computer and use it in GitHub Desktop.
setInterval 在 React hooks 中的实现
import { useEffect, useRef } from 'react'
function useInterval(callback, delay) {
const savedCallback = useRef(callback)
// Remember the latest callback if it changes.
useEffect(() => {
savedCallback.current = callback
}, [callback])
// Set up the interval.
useEffect(() => {
// Don't schedule if no delay is specified.
// Note: 0 is a valid value for delay.
if (!delay && delay !== 0) {
return
}
const id = setInterval(() => savedCallback.current(), delay)
return () => clearInterval(id)
}, [delay])
}
export default useInterval
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment