Last active
May 8, 2025 15:59
-
-
Save GeDiez/01c956d93fe04672ba583b11e6807397 to your computer and use it in GitHub Desktop.
Simple Timer
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
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