From 6ac00088f8167693898f5736d6508ec1065e4c94 Mon Sep 17 00:00:00 2001 From: XYShaoKang <38753204+XYShaoKang@users.noreply.github.com> Date: Sat, 17 Jun 2023 17:22:19 +0800 Subject: [PATCH] =?UTF-8?q?fix(problems):=20=E5=A2=9E=E5=8A=A0=E6=97=B6?= =?UTF-8?q?=E9=92=9F=E6=9B=B4=E6=96=B0=E9=A2=91=E7=8E=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 修复导致计时器显示有时会卡一秒的 bug --- src/content/pages/problems/useTimer.ts | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/src/content/pages/problems/useTimer.ts b/src/content/pages/problems/useTimer.ts index 1d40d6c..bc967a6 100644 --- a/src/content/pages/problems/useTimer.ts +++ b/src/content/pages/problems/useTimer.ts @@ -1,4 +1,4 @@ -import { useEffect, useRef, useState } from 'react' +import { useEffect, useMemo, useRef, useState } from 'react' import { logger } from '../../../utils' const log = logger.child({ prefix: 'useTimer' }) @@ -6,7 +6,6 @@ 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) @@ -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 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 () => { @@ -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 }