Last active
October 4, 2025 18:37
-
-
Save Wigny/a25664567c3d7c60d145b24833b9b54a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { useCallback, useRef } from 'react'; | |
| import { duration } from 'dayjs'; | |
| import { type Duration } from 'dayjs/plugin/duration'; | |
| type Timer = { | |
| start: () => void; | |
| pause: () => Duration; | |
| resume: () => void; | |
| reset: () => void; | |
| }; | |
| export function useTimer(): Timer { | |
| const elapsedTime = useRef(duration(0)); | |
| const startTime = useRef<DOMHighResTimeStamp | null>(null); | |
| const start = useCallback(() => { | |
| elapsedTime.current = duration(0); | |
| startTime.current = performance.now(); | |
| }, []); | |
| const pause = useCallback(() => { | |
| if (startTime.current !== null) { | |
| const deltaTime = duration(performance.now() - startTime.current); | |
| elapsedTime.current = elapsedTime.current.add(deltaTime); | |
| } | |
| startTime.current = null; | |
| return elapsedTime.current; | |
| }, []); | |
| const resume = useCallback(() => { | |
| if (startTime.current === null) { | |
| startTime.current = performance.now(); | |
| } | |
| }, []); | |
| const reset = useCallback(() => { | |
| elapsedTime.current = duration(0); | |
| startTime.current = null; | |
| }, []); | |
| return { start, pause, resume, reset }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment