From 4171829a15a55383a319b2a69908b59d3d88e630 Mon Sep 17 00:00:00 2001 From: hamster1963 <1410514192@qq.com> Date: Wed, 19 Feb 2025 14:26:22 +0800 Subject: [PATCH] feat: optimize time display rendering with requestAnimationFrame --- app/(main)/header.tsx | 34 +++++++++++++++++++++++++--------- 1 file changed, 25 insertions(+), 9 deletions(-) diff --git a/app/(main)/header.tsx b/app/(main)/header.tsx index b3440aa..be30659 100644 --- a/app/(main)/header.tsx +++ b/app/(main)/header.tsx @@ -30,16 +30,32 @@ const useCurrentTime = () => { }) useEffect(() => { - const timer = setInterval(() => { - const now = DateTime.now().setLocale("en-US") - setTime({ - hh: now.hour, - mm: now.minute, - ss: now.second, - }) - }, 1000) + let animationFrameId: number + let lastSecond = DateTime.now().setLocale("en-US").second - return () => clearInterval(timer) + const updateTime = () => { + const now = DateTime.now().setLocale("en-US") + const currentSecond = now.second + + if (currentSecond !== lastSecond) { + lastSecond = currentSecond + setTime({ + hh: now.hour, + mm: now.minute, + ss: currentSecond, + }) + } + + animationFrameId = requestAnimationFrame(updateTime) + } + + animationFrameId = requestAnimationFrame(updateTime) + + return () => { + if (animationFrameId) { + cancelAnimationFrame(animationFrameId) + } + } }, []) return time