Created
October 12, 2021 17:44
-
-
Save James-Bovis/0ace7611f36ecb64747523b734fff2f3 to your computer and use it in GitHub Desktop.
useStopwatch.ts
This file contains 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
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