繁体   English   中英

如何在后端创建一个对每个用户都是唯一的计时器,可以使用 socketio 事件清除它

[英]How can I make a timer on the backend that is unique to every user which can be cleared using socketio events

我正在使用 MERN 堆栈和 SocketIO 制作基于回合的多人游戏。 我希望每个玩家在游戏将他们踢出局之前有 60 秒的时间轮到他们上场。 一旦该玩家播放,我希望取消计时器。 我尝试为游戏中的每个玩家创建一个 setTimeout function,然后使用 clearTimeout 根据 socketIO 事件取消计时器,但计时器实际上并没有被取消。 这可能是一个实现问题,所以我想知道实现此功能的最佳方法是什么? 这是我当前的实现:

socket.on('Start Countdown', () => {
    let user = getUser(socket.id);
    user.countDown = setTimeout(() => {
      socket.emit('Error', { error: { msg: 'You took too long' } });
      socket.emit('AFK');
    }, 60000);
  });
  socket.on('Stop Countdown', () => {
    let user = getUser(socket.id);
    if (user.countDown) {
      clearTimeout(user.countDown);
      console.log(user.countDown);
    }
    console.log(user.countDown);
  });

如前所述,当“停止倒计时”发生时,计时器不会被取消。 注意:getUser 根据提供的 socket.id 从 users 数组返回一个 js object, user,形式为 {socketId, userId, roomId, countDown}。 该数组中不会有两个元素具有相同的 userId,刷新后,socketId 元素将更新为正确的 socket.id。 因此,您可以假设 getUser 每次都会返回相同的用户 object,即使在刷新之后也是如此。

猜猜应该可以,但是您可以尝试定义一个新的空 object,其 ID 是 client.id,因此您可以为其分配 setTimeout 值,从那里您可以检查是否有一个计时器已经为该用户运行或取消它在最后。

const timers = {};

socket.on('Start Countdown', () => {
    if (typeof timers[socket.id] !== 'undefined') {
        clearTimeout(timers[socket.id]);
    }

    timers[socket.id] = setTimeout(() => {
        socket.emit('Error', { error: { msg: 'You took too long' } });
        socket.emit('AFK');
    }, 60000);
});

socket.on('Stop Countdown', () => {
    if (typeof timers[socket.id] !== 'undefined') {
        clearTimeout(timers[socket.id]);
        delete timers[socket.id];
    }
});

希望对你有帮助!

我不知道getUser是如何工作的,但是如果从数据库中获取user var 在Start Countdown事件结束时被销毁,您可以尝试定义一个 object 并分配用户的一些唯一属性,例如idusername键和超时作为值:


var timeouts = {} //this must go outside the socket connection event

socket.on('Start Countdown', () => {
    let user = getUser(socket.id);
    //it could be user.id, user.username or some property of user that is unique and unvariable
    timeouts[user.userId] = setTimeout(() => {
      socket.emit('Error', { error: { msg: 'You took too long' } });
      socket.emit('AFK');
    }, 60000);
  });
  socket.on('Stop Countdown', () => {
    let user = getUser(socket.id);
    if (timeouts[user.userId]) {
      clearTimeout(timeouts[user.userId]);
      console.log(timeouts[user.userId]);
    }
    console.log(timeouts[user.userId]);
  });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM