Skip to content

Instantly share code, notes, and snippets.

@sebassdc
Created March 23, 2020 16:41
Show Gist options
  • Save sebassdc/033ef5c0a748c0e1e05f6882e69c416a to your computer and use it in GitHub Desktop.
Save sebassdc/033ef5c0a748c0e1e05f6882e69c416a to your computer and use it in GitHub Desktop.
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