agentic-rag / frontend /src /hooks /useElapsedTimer.ts
vksepm
updated ui
0dcdb24
Raw
History Blame Contribute Delete
1.07 kB
import { useEffect, useRef, useState } from "react";
/**
* Returns a human-readable elapsed time string ("3s", "1m 4s") that updates
* every second while `running` is true. Resets to "" when running flips to true.
*/
export function useElapsedTimer(running: boolean): string {
const [elapsed, setElapsed] = useState(0);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
useEffect(() => {
if (running) {
setElapsed(0);
intervalRef.current = setInterval(() => {
setElapsed((s) => s + 1);
}, 1000);
} else {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
}
return () => {
if (intervalRef.current !== null) {
clearInterval(intervalRef.current);
intervalRef.current = null;
}
};
}, [running]);
if (!running && elapsed === 0) return "";
const minutes = Math.floor(elapsed / 60);
const seconds = elapsed % 60;
return minutes > 0 ? `${minutes}m ${seconds}s` : `${elapsed}s`;
}