如何通过socket事件停止setTimeOut?

问题描述 投票:0回答:1

我有一个程序,客户端可以通过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 which Timeout ID?
})

我感谢任何形式的帮助!

javascript angular sockets settimeout setinterval
1个回答
1
投票

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

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
})
© www.soinside.com 2019 - 2024. All rights reserved.