Created
May 2, 2022 09:55
-
-
Save jacob-lcs/0c91e387a22a2a09a72b16f7d8ac9e74 to your computer and use it in GitHub Desktop.
setInterval 在 React hooks 中的实现
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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