Skip to content

Instantly share code, notes, and snippets.

@Wigny
Last active October 4, 2025 18:37
Show Gist options
  • Select an option

  • Save Wigny/a25664567c3d7c60d145b24833b9b54a to your computer and use it in GitHub Desktop.

Select an option

Save Wigny/a25664567c3d7c60d145b24833b9b54a to your computer and use it in GitHub Desktop.
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