Skip to content

Instantly share code, notes, and snippets.

@mbchoa
Created April 18, 2021 05:29
Show Gist options
  • Save mbchoa/9367f13672bcb113671ff70c4f7ec433 to your computer and use it in GitHub Desktop.
Save mbchoa/9367f13672bcb113671ff70c4f7ec433 to your computer and use it in GitHub Desktop.
React Hook for millisecond-precision stopwatch timer.
import { useState, useRef } from 'react';
const useTimer = (initialState = 0) => {
const [elapsedTime, setElapsedTime] = useState(initialState);
const [isRunning, setIsRunning] = useState(false);
const countRef = useRef(null);
const handleStart = () => {
const startTime = Date.now() - elapsedTime;
countRef.current = setInterval(() => {
setElapsedTime(Date.now() - startTime);
}, 10);
setIsRunning(true);
}
const handlePause = () => {
clearInterval(countRef.current);
setIsRunning(false);
}
const handleReset = () => {
clearInterval(countRef.current);
setIsRunning(false);
setElapsedTime(0);
}
return { elapsedTime, isRunning, handleStart, handlePause, handleReset };
}
export default useTimer;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment