Skip to content

Commit

Permalink
fix(problems): 增加时钟更新频率
Browse files Browse the repository at this point in the history
修复导致计时器显示有时会卡一秒的 bug
  • Loading branch information
XYShaoKang committed Jun 17, 2023
1 parent 7881724 commit 6ac0008
Showing 1 changed file with 9 additions and 8 deletions.
17 changes: 9 additions & 8 deletions src/content/pages/problems/useTimer.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
import { useEffect, useRef, useState } from 'react'
import { useEffect, useMemo, useRef, useState } from 'react'
import { logger } from '../../../utils'

const log = logger.child({ prefix: 'useTimer' })

type Time = [house: number, minute: number, second: number]

function formatTime(time: number): Time {
time = time / 1000
const house = Math.floor(time / 3600)
const minute = Math.floor((time / 60) % 60)
const second = Math.floor(time % 60)
Expand All @@ -27,14 +26,17 @@ type UseTimeReturn = {
const useTimer = (): UseTimeReturn => {
const start = useRef(new Date())
const [isDone, setIsDone] = useState(false)
const [time, setTime] = useState(formatTime(0))
const [value, setValue] = useState(0)
const time = useMemo(() => {
return formatTime(value)
}, [value])

useEffect(() => {
let timer: ReturnType<typeof setInterval>
if (!isDone) {
timer = setInterval(async () => {
setTime(formatTime(new Date().valueOf() - start.current.valueOf()))
}, 1000)
setValue(Math.floor((Date.now() - start.current.valueOf()) / 1000))
}, 100)
}

return () => {
Expand All @@ -48,13 +50,12 @@ const useTimer = (): UseTimeReturn => {
log.debug('重新开始计时')
setIsDone(false)
start.current = new Date()
setTime(formatTime(0))
setValue(0)
}

const done = (time: Time) => {
const done = () => {
log.debug('结束计时')
setIsDone(true)
setTime(time)
}

return { time, isDone, done, restart }
Expand Down

0 comments on commit 6ac0008

Please sign in to comment.