Skip to content

Instantly share code, notes, and snippets.

@GeDiez
Last active May 8, 2025 15:59
Show Gist options
  • Save GeDiez/01c956d93fe04672ba583b11e6807397 to your computer and use it in GitHub Desktop.
Save GeDiez/01c956d93fe04672ba583b11e6807397 to your computer and use it in GitHub Desktop.
Simple Timer
const timer = ({ interval = 1000, onTime = () => {} }) => {
let time = 0;
let pid = null;
const stop = () => {
clearInterval(pid);
};
const start = () => {
pid = setInterval(() => {
time += 1;
onTime(time);
}, interval);
};
return {
stop,
start,
};
};
const useTimer = (options) => {
const [time, setTime] = useState(0);
const timerRef = useRef(timer({
...options,
onTime: (t) => setTime(t),
}));
return {
time,
stop: timerRef.current.stop,
start: timerRef.current.start,
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment