You need to enable JavaScript to run this app. 基于Redis与WebSocket开发多设备同步游戏计时器时递归触发栈溢出错误
优惠活动
大模型
产品
解决方案
定价
更多

基于Redis与WebSocket开发多设备同步游戏计时器时递归触发栈溢出错误

错误根源定位

这个栈溢出错误和node-redis的publish阻塞特性完全无关,所有问题都来自JavaScript定时器的错误使用逻辑:

  • 直接触发栈溢出的核心代码段是:
    let ticker = setInterval(tick(newTime, publisher), 1000)
    
    这行代码的执行逻辑是:先立刻同步执行tick(newTime, publisher)拿到返回值,再把返回值作为setInterval的回调传入。由于tick函数没有显式返回值,实际传给setInterval的回调是undefined,而同步执行的那一步会直接无限递归调用tick函数——没有任何延时等待,调用栈被层层嵌套的函数调用持续占用,直到栈空间超限抛出RangeError。

除了触发栈溢出的核心问题,当前实现还存在多处逻辑缺陷:

  • 就算修复了递归触发的问题,代码每次进入tick都会新建一个setInterval实例,没有清理上一次创建的定时器,最终会存在大量并行运行的重复计时任务,重复向Redis发布计时消息,完全偏离单一定时器的预期效果。
  • 每次进入tick都会给同一个Redis客户端实例绑定新的message事件监听,随着递归执行会产生大量重复的事件回调,造成内存泄漏和逻辑混乱。
  • node-redis的publish方法是异步非阻塞的网络IO操作,根本不会阻塞同步执行栈,不存在因为方法阻塞导致栈溢出的可能。
正确实现调整方案

要实现稳定的跨设备同步计时逻辑,需要按照以下方向调整:

  • 定时器回调必须传入函数引用,需要传递参数时用闭包包一层,不要在setInterval的参数位置直接执行函数
  • 全局只维护一个定时器实例,不要每次计时循环都新建定时器
  • Redis的message事件监听全局只绑定一次,不要反复重复注册
  • 停止计时时直接清除全局唯一的定时器实例即可

调整后的参考实现:

// 全局维护单一定时器实例,避免重复创建
let timerInstance: NodeJS.Timeout | null = null;
// 存储当前计时值
let currentTime: Time = { minutes: 4, seconds: 0 };

const tick = (publisher: RedisClient) => {
  // 计算下一秒的时间值
  if (currentTime.seconds === 0) {
    if (currentTime.minutes === 0) {
      currentTime = { minutes: 4, seconds: 0 };
    } else {
      currentTime = { minutes: currentTime.minutes - 1, seconds: 59 };
    }
  } else {
    currentTime = { ...currentTime, seconds: currentTime.seconds - 1 };
  }
  // 向Redis频道发布当前计时值,供所有订阅端同步
  publisher.publish("scoring:timer", `${currentTime.minutes}: ${currentTime.seconds}`);
}

function startTimer() {
  const publisher = createClient();
  publisher.publish("scoring:events", "START");
  // 初始化计时值
  currentTime = { minutes: 4, seconds: 0 };

  // 仅绑定一次停止事件的监听逻辑
  publisher.on("message", (channel, message) => {
    if (message === "STOP" && timerInstance) {
      clearInterval(timerInstance);
      timerInstance = null;
    }
  });

  // 创建单一定时器,每秒触发一次计时更新
  timerInstance = setInterval(() => tick(publisher), 1000);
}

内容的提问来源于stack exchange,提问作者Sam Roehrich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 04:06:00