MCPcopy
hub / github.com/gre/gl-react / useTimeLoop

Function useTimeLoop

packages/cookbook/src/hooks/useTimeLoop.ts:3–30  ·  view source on GitHub ↗
(refreshRate = 60)

Source from the content-addressed store, hash-verified

1import { useState, useEffect, useRef } from "react";
2
3export function useTimeLoop(refreshRate = 60) {
4 const [state, setState] = useState({ time: 0, tick: 0 });
5 const rafRef = useRef<number>();
6
7 useEffect(() => {
8 let startTime: number | undefined;
9 let lastTime = -(1000 / refreshRate);
10 const interval = 1000 / refreshRate;
11
12 const loop = (t: number) => {
13 rafRef.current = requestAnimationFrame(loop);
14 if (startTime === undefined) startTime = t;
15 if (t - lastTime > interval) {
16 lastTime = t;
17 setState((prev) => ({
18 time: t - startTime!,
19 tick: prev.tick + 1,
20 }));
21 }
22 };
23 rafRef.current = requestAnimationFrame(loop);
24 return () => {
25 if (rafRef.current) cancelAnimationFrame(rafRef.current);
26 };
27 }, [refreshRate]);
28
29 return state;
30}

Callers 15

HeroDemoFunction · 0.90
DesertPassageFunction · 0.90
SlideshowFunction · 0.90
DemoDesertFunction · 0.90
DiamondAnimFunction · 0.90
PreviewFunction · 0.90
DemoTunnelFunction · 0.90
SDF1Function · 0.90
GameOfLifeWebcamFunction · 0.90
ConicalGradiantLoopFunction · 0.90
BehindAsteroidsFunction · 0.90
GOLFunction · 0.90

Calls

no outgoing calls

Tested by

no test coverage detected

Used in the wild real call sites across dependent graphs

searching dependent graphs…