[fix] update data lost between page and stutter caused by periodly checking game stats in sync mode

This commit is contained in:
2025-11-09 00:55:19 +08:00
parent 812bc64b6f
commit 0f938f6f3e
10 changed files with 190 additions and 94 deletions

View File

@@ -0,0 +1,65 @@
import { useEffect, useRef } from "react"
import { useToolStore } from "@/store/tool"
// 全局检测间隔(毫秒)- 增加到5秒以减少性能影响
const CHECK_INTERVAL = 5000
// 全局检测状态管理
let globalInterval: NodeJS.Timeout | null = null
let subscriberCount = 0
/**
* 全局游戏状态监控 Hook
* 多个组件可以共享同一个检测循环,避免重复检测
*
* @param enabled 是否启用检测(默认 true
* @returns 游戏运行状态和手动检测函数
*/
export function useGlobalGameMonitor(enabled: boolean = true) {
const tool = useToolStore()
const isGameRunning = tool.state.isGameRunning
const checkGameRunning = tool.checkGameRunning
const enabledRef = useRef(enabled)
// 更新 enabled 引用
useEffect(() => {
enabledRef.current = enabled
}, [enabled])
useEffect(() => {
if (!enabled) {
return
}
// 增加订阅者计数
subscriberCount++
// 如果这是第一个订阅者,启动全局检测循环
if (subscriberCount === 1) {
// 立即检测一次
void checkGameRunning()
// 启动定期检测
globalInterval = setInterval(() => {
void checkGameRunning()
}, CHECK_INTERVAL)
}
// 清理函数:减少订阅者计数
return () => {
subscriberCount--
// 如果没有订阅者了,停止检测循环
if (subscriberCount === 0 && globalInterval) {
clearInterval(globalInterval)
globalInterval = null
}
}
}, [enabled, checkGameRunning])
return {
isGameRunning,
checkGameRunning,
}
}