javascript - 如何通过套接字事件停止setTimeOut?

标签 javascript angular sockets settimeout setinterval

我有一个程序,客户端可以通过socket.io“createTimer”。然后,服务器每秒向同一房间中的所有客户端发送一次。 当超时达到最大重复次数时,客户端会发生一些事情,因为时间 = 0。到目前为止一切顺利。但在特殊情况下,我必须在完成之前清除超时。但我不知道如何调用clearTimeout。我对 setInterval 也有同样的问题。这是我的代码:

socket.on('createTimer', data => {
 interval(function(){
  io.sockets.in(data.roomID).emit('newTime',{time:data.time--});
   }, 
 1000, data.time+1);
 })

 function interval(func, wait, times){
    var interv = function(w, t){
        return function(){
           if(typeof t === "undefined" || t-- > 0){
             setTimeout(interv, w);
             try{
                 func.call(null);
             }
             catch(e){
                 t = 0;
                 throw e.toString();
             }
           }
        };
   }(wait, times);
   setTimeout(interv, wait);
};

 socket.on('setTimerZero', roomID =>{
  // how can I use clearTimeout here? with wich Timeout ID ?
})

非常感谢您提供的任何帮助!

最佳答案

您可以存储每个房间的超时,然后可以清除它们:

var timeouts={};
socket.on('createTimer', data => {
     setInterval(function(){
         io.sockets.in(data.roomID).emit('newTime',{time:data.time--});
     }, 1000, data.time+1,data.roomID);//pass it
})

function interval(func, wait, times,id){
    var interv = (function(w, t){
        return function(){
            if(typeof t === "undefined" || t-- > 0){
                timeouts[id]=setTimeout(interv, w);
                try{
                    func.call(null);
                }
                catch(e){
                    t = 0;
                    throw e.toString();
                }
            }
        };
    })(wait, times);//better with parenthesis
    timeouts[id]=setTimeout(interv, wait);//store it
}

socket.on('setTimerZero', room =>{
    if(timeouts[room.roomID]) clearTimeout(timeouts[room.roomID]), timeouts[room.roomID]=null;//clear if they exist
})

关于javascript - 如何通过套接字事件停止setTimeOut?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44141731/

相关文章:

javascript - 插入 div 时运行脚本

angular - 如何在客户端以 Angular 解码 JWT 编码的 token 有效负载?

javascript - 从对象列表中删除项目 - Typescript

linux - 如何绑定(bind)到只有一个网络接口(interface)(Linux)的所有地址?

java - JButton 的图标没有改变(UNO 纸牌游戏)

mysql - perl tcp 套接字服务器到 mysql

javascript - 修改公共(public) npm 包中的一些功能

javascript - 如何使用 Ramda 编写 point-free 函数式 JS

javascript - 未捕获错误 : _registerComponent(. ..):目标容器不是 DOM 元素

angular - 组件不是已知元素 [Angular]