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, } }