Skip to content

Instantly share code, notes, and snippets.

@James-Bovis
Created October 12, 2021 17:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save James-Bovis/0ace7611f36ecb64747523b734fff2f3 to your computer and use it in GitHub Desktop.
Save James-Bovis/0ace7611f36ecb64747523b734fff2f3 to your computer and use it in GitHub Desktop.
useStopwatch.ts
import * as React from 'react'
type UseStopwatch = {
seconds: number,
startStopwatch: () => void,
stopStopwatch: () => void,
resetStopwatch: () => void
}
const useStopwatch = (): UseStopwatch => {
const [seconds, setSeconds] = React.useState(20)
const [stopwatchRunning, setStopwatchRunning] = React.useState(false)
const startStopwatch = (): void => {
setStopwatchRunning(true)
}
const stopStopwatch = (): void => {
setStopwatchRunning(false)
}
const resetStopwatch = (): void => {
stopStopwatch()
setSeconds(20)
}
React.useEffect(() => {
const interval = setInterval((): void => {
if (stopwatchRunning && seconds > 0) {
setSeconds(seconds - 1)
}
if (stopwatchRunning && seconds === 0) {
clearInterval(interval)
}
}, 1000)
return () => clearInterval(interval)
}, [seconds, stopwatchRunning])
return {
seconds,
startStopwatch,
stopStopwatch,
resetStopwatch
}
}
export default useStopwatch
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment