UNPKG

react-use-stopwatch

Version:
71 lines (57 loc) 1.8 kB
import { useState } from "react"; const pad = (n: number) => (String(n) as any).padStart(2, "0").substring(0, 2); type StopwatchAction = () => void; type StopwatchTime = { time: number; format: string }; type StopwatchType = () => [ StopwatchTime, StopwatchAction, StopwatchAction, StopwatchAction ]; export const useStopwatch: StopwatchType = () => { const [timerId, setTimerId] = useState(); const [time, setTime] = useState({ time: 0, format: "00:00:00.00" }); const start: StopwatchAction = () => { setTimerId( setInterval(() => { setTime((time: StopwatchTime) => { let remainingTime: number = time.time + 10; let hours: number = 0; let minutes: number = 0; let seconds: number = 0; let milliseconds: number = 0; if (remainingTime / 3600000 >= 1) { hours = Math.floor(remainingTime / 3600000); remainingTime -= hours * 3600000; } if (remainingTime / 60000 >= 1) { minutes = Math.floor(remainingTime / 60000); remainingTime -= minutes * 60000; } if (remainingTime / 1000 >= 1) { seconds = Math.floor(remainingTime / 1000); remainingTime -= seconds * 1000; } milliseconds = remainingTime / 10; return { time: time.time + 10, format: `${pad(hours)}:${pad(minutes)}:${pad(seconds)}.${pad( milliseconds )}` }; }); }, 10) ); }; const stop: StopwatchAction = () => { clearInterval(timerId); }; const reset: StopwatchAction = () => { clearInterval(timerId); setTime({ time: 0, format: "00:00:00.00" }); }; return [time, start, stop, reset]; };