Created
March 26, 2025 09:28
-
-
Save hrdyjan1/5f6c3073ffb941af9f5dcf6eea8cd18e to your computer and use it in GitHub Desktop.
Custom hook that calls a callback every second using requestAnimationFrame.
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
| import { useEffect, useRef } from 'react'; | |
| function useRequestAnimationFrame(isRunning: boolean, callback: () => void) { | |
| const interval = 1000; // 1 second in milliseconds | |
| const startTimeRef = useRef<number | null>(null); // Track the start time | |
| const animationFrameIdRef = useRef<number | null>(null); // Track the animation frame ID | |
| useEffect(() => { | |
| if (!isRunning) { | |
| // If not running, cancel any ongoing animation frame | |
| if (animationFrameIdRef.current) { | |
| cancelAnimationFrame(animationFrameIdRef.current); | |
| } | |
| return; | |
| } | |
| const step = (timestamp: number) => { | |
| if (!startTimeRef.current) { | |
| startTimeRef.current = timestamp; // Initialize start time | |
| } | |
| const elapsed = timestamp - startTimeRef.current; | |
| if (elapsed >= interval) { | |
| callback(); // Call the provided callback | |
| startTimeRef.current = timestamp; // Reset start time | |
| } | |
| animationFrameIdRef.current = requestAnimationFrame(step); // Request next frame | |
| }; | |
| animationFrameIdRef.current = requestAnimationFrame(step); // Start animation | |
| return () => { | |
| if (animationFrameIdRef.current) { | |
| cancelAnimationFrame(animationFrameIdRef.current); | |
| } | |
| }; | |
| }, [callback, isRunning]); // Re-run if the callback or isRunning changes | |
| } | |
| export default useRequestAnimationFrame; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment