MCPcopy Create free account
hub / github.com/anus-dev/ANUS / useTimer

Function useTimer

packages/cli/src/ui/hooks/useTimer.ts:16–66  ·  view source on GitHub ↗
(isActive: boolean, resetKey: unknown)

Source from the content-addressed store, hash-verified

14 * @returns The elapsed time in seconds.
15 */
16export const useTimer = (isActive: boolean, resetKey: unknown) => {
17 const [elapsedTime, setElapsedTime] = useState(0);
18 const timerRef = useRef<NodeJS.Timeout | null>(null);
19 const prevResetKeyRef = useRef(resetKey);
20 const prevIsActiveRef = useRef(isActive);
21
22 useEffect(() => {
23 let shouldResetTime = false;
24
25 if (prevResetKeyRef.current !== resetKey) {
26 shouldResetTime = true;
27 prevResetKeyRef.current = resetKey;
28 }
29
30 if (prevIsActiveRef.current === false && isActive) {
31 // Transitioned from inactive to active
32 shouldResetTime = true;
33 }
34
35 if (shouldResetTime) {
36 setElapsedTime(0);
37 }
38 prevIsActiveRef.current = isActive;
39
40 // Manage interval
41 if (isActive) {
42 // Clear previous interval unconditionally before starting a new one
43 // This handles resetKey changes while active, ensuring a fresh interval start.
44 if (timerRef.current) {
45 clearInterval(timerRef.current);
46 }
47 timerRef.current = setInterval(() => {
48 setElapsedTime((prev) => prev + 1);
49 }, 1000);
50 } else {
51 if (timerRef.current) {
52 clearInterval(timerRef.current);
53 timerRef.current = null;
54 }
55 }
56
57 return () => {
58 if (timerRef.current) {
59 clearInterval(timerRef.current);
60 timerRef.current = null;
61 }
62 };
63 }, [isActive, resetKey]);
64
65 return elapsedTime;
66};

Callers 2

useLoadingIndicatorFunction · 0.85
useTimer.test.tsFile · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected