Created
March 23, 2020 16:41
-
-
Save sebassdc/033ef5c0a748c0e1e05f6882e69c416a to your computer and use it in GitHub Desktop.
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 { useState, useRef, useEffect } from 'react' | |
export const useTimer = ({ initialStartTime = 0, shouldStartOnMount = false }) => { | |
const [milliseconds, setMilliSeconds] = useState(0) | |
const intervalRef = useRef() | |
const startTime = useRef() | |
const play = () => { | |
if (intervalRef.current) return | |
if (!startTime.current) { | |
startTime.current = new Date().getTime() | |
} | |
intervalRef.current = setInterval(() => { | |
const deltaTime = new Date().getTime() - startTime.current | |
setMilliSeconds(deltaTime) | |
}, 200) | |
} | |
const stop = () => { | |
if (!intervalRef.current) return | |
clearInterval(intervalRef.current) | |
intervalRef.current = null | |
startTime.current = null | |
setMilliSeconds(0) | |
} | |
useEffect(() => { | |
if (initialStartTime) { | |
startTime.current = initialStartTime | |
} | |
if (shouldStartOnMount) { | |
play() | |
} | |
}, [initialStartTime, shouldStartOnMount]) | |
return { milliseconds, play, stop, startTime: startTime.current } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment