keepme / src /hooks /useTimer.ts
narinder1231's picture
Add useTimer hook for managing a timer with start, stop, and formatting functionality
9b0016a
raw
history blame contribute delete
820 Bytes
import { useState, useRef } from "react";
export function useTimer() {
const [seconds, setSeconds] = useState(0);
const intervalRef = useRef<ReturnType<typeof setInterval> | null>(null);
function startTimer() {
setSeconds(0);
intervalRef.current = setInterval(() => {
setSeconds((prev) => prev + 1);
}, 1000);
}
function stopTimer() {
if (intervalRef.current) {
clearInterval(intervalRef.current);
}
setSeconds(0);
}
function formatTime(seconds: number) {
const hrs = Math.floor(seconds / 3600);
const mins = Math.floor((seconds % 3600) / 60);
const secs = seconds % 60;
return `${String(hrs).padStart(2, "0")}:${String(mins).padStart(2, "0")}:${String(secs).padStart(2, "0")}`;
}
return { timer: formatTime(seconds), startTimer, stopTimer };
}