From 69903ff464f86ae58667505418b78f2a3624f8e6 Mon Sep 17 00:00:00 2001 From: Lei OT Date: Mon, 9 Dec 2024 17:18:06 +0800 Subject: [PATCH] =?UTF-8?q?perf:=20requestAnimationFrame=20=E4=BB=A3?= =?UTF-8?q?=E6=9B=BF=20setInternal=20,=20=E6=80=A7=E8=83=BD=E9=97=AE?= =?UTF-8?q?=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/views/DesktopApp.jsx | 50 ++++++++++++++++++++++++++++------------ 1 file changed, 35 insertions(+), 15 deletions(-) diff --git a/src/views/DesktopApp.jsx b/src/views/DesktopApp.jsx index ecefef7..ae064c8 100644 --- a/src/views/DesktopApp.jsx +++ b/src/views/DesktopApp.jsx @@ -18,7 +18,7 @@ import { Drawer, } from 'antd' import 'dayjs/locale/zh-cn' -import { useEffect, useState } from 'react' +import { useEffect, useState, useCallback, useRef } from 'react' import { Link, NavLink, Outlet, useHref } from 'react-router-dom' import '@/assets/App.css' @@ -88,26 +88,46 @@ function DesktopApp() { * 标签页标题闪烁 */ const [isTitleVisible, setIsTitleVisible] = useState(true) + + const start = useRef(); + useEffect(() => { - let interval - if (totalNotify > 0) { - if ('setAppBadge' in navigator) { - navigator.setAppBadge(totalNotify).catch(() => {}) + let animationFrameId; + + const step = (timestamp) => { + if (start.current === undefined) { + start.current = timestamp; } - interval = setInterval(() => { + const elapsed = timestamp - start.current; + + if (elapsed > 1000) { // 2000ms = 2s document.title = isTitleVisible ? `🔔🔥💬【${totalNotify}条新消息】` - : '______________' - setIsTitleVisible(!isTitleVisible) - }, 500) - } else { - document.title = '销售平台' - if ('clearAppBadge' in navigator) { - navigator.clearAppBadge().catch(() => {}) + : '______________'; + setIsTitleVisible(!isTitleVisible); + start.current = timestamp; + } + + if (totalNotify > 0) { + animationFrameId = requestAnimationFrame(step); + } else { + document.title = '销售平台'; } + }; + + if (totalNotify > 0) { + if ('setAppBadge' in navigator) { + navigator.setAppBadge(totalNotify).catch(() => {}); + } + animationFrameId = requestAnimationFrame(step); } - return () => clearInterval(interval) - }, [totalNotify, isTitleVisible]) + + return () => { + if (animationFrameId) { + cancelAnimationFrame(animationFrameId); + } + }; + }, [totalNotify, isTitleVisible]); return (