Skip to content

Instantly share code, notes, and snippets.

@hrdyjan1
Created March 26, 2025 09:28
Show Gist options
  • Select an option

  • Save hrdyjan1/5f6c3073ffb941af9f5dcf6eea8cd18e to your computer and use it in GitHub Desktop.

Select an option

Save hrdyjan1/5f6c3073ffb941af9f5dcf6eea8cd18e to your computer and use it in GitHub Desktop.
Custom hook that calls a callback every second using requestAnimationFrame.
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