Skip to content

Commit

Permalink
Fix timer being unreliable
Browse files Browse the repository at this point in the history
This unrealiablity was due to the setInterval behaviour, instead of
adding one second each interval it compares the startTIme with the
current time.
  • Loading branch information
negreirosleo committed Jan 31, 2024
1 parent 5443e6d commit ef83d4a
Showing 1 changed file with 10 additions and 6 deletions.
16 changes: 10 additions & 6 deletions frontend/src/hooks/useTimer/useTimer.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,26 @@
import { useState, useEffect, useCallback } from 'react'
import { useState, useEffect, useCallback, useMemo } from 'react'

export const useTimer = () => {
const [time, setTime] = useState(0)
const [isTimerRunning, setIsTimerRunning] = useState(false)
const [startTime, setStartTime] = useState(0)

const startTimer = useCallback(() => setIsTimerRunning(true), [])
const startTimer = useCallback(() => {
setStartTime(Date.now())
}, [])
const stopTimer = useCallback(() => {
setIsTimerRunning(false)
setStartTime(0)
setTime(0)
}, [])

const isTimerRunning = useMemo(() => startTime > 0, [startTime])

useEffect(() => {
let intervalId: NodeJS.Timeout | undefined
if (isTimerRunning) {
intervalId = setInterval(() => setTime((prevTime) => prevTime + 1), 1000)
intervalId = setInterval(() => setTime((Date.now() - startTime) / 1000), 1000)
}
return () => clearInterval(intervalId)
}, [isTimerRunning])
}, [isTimerRunning, startTime])

const seconds = Math.floor(time % 60)
const minutes = Math.floor((time / 60) % 60)
Expand Down

0 comments on commit ef83d4a

Please sign in to comment.