Last active
February 8, 2025 18:11
-
-
Save manix84/38f5065bad4b16b471932ca7a8ea349c to your computer and use it in GitHub Desktop.
A react hook for setInterval
This file contains hidden or 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
| /** | |
| This code is licensed under the terms of the MIT license | |
| */ | |
| import { useEffect, useRef } from 'react'; | |
| export const useInterval = (callback: () => void, delay: number): [() => void] => { | |
| const intervalIdRef = useRef<number | null>(null); | |
| useEffect(() => { | |
| intervalIdRef.current = window.setInterval(callback, delay); | |
| return () => { | |
| if (intervalIdRef.current !== null) { | |
| window.clearInterval(intervalIdRef.current); | |
| } | |
| }; | |
| }, [callback, delay]); | |
| const clearInterval = () => { | |
| if (intervalIdRef.current !== null) { | |
| window.clearInterval(intervalIdRef.current); | |
| intervalIdRef.current = null; | |
| } | |
| }; | |
| return [clearInterval]; | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment