【问题标题】:How to stop setTimeOut via socket event?如何通过套接字事件停止 setTimeOut?
【发布时间】:2017-05-23 17:47:44
【问题描述】:

我有一个程序,客户端可以通过 socket.io 'createTimer'。然后,服务器每秒向同一房间内的所有客户端发送一次。 当超时达到他的最大重复次数时,客户端会发生一些事情,因为时间 = 0。到目前为止一切都很好。但在特殊情况下,我必须在 Timeout 完成之前清除它。但我不知道如何调用 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 ?
})

感谢您的任何帮助!

【问题讨论】:

  • 同时运行不同的超时,因此我不能使用局部变量作为超时 ID

标签: javascript angular sockets settimeout setinterval


【解决方案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
})

【讨论】:

  • 我已经试过了。由于'setTimerZero'中的console.log,我看到这个事件被正确调用,但时间一直在运行。 Timout 不会停止。
  • @mcAngular2 你可能不会尝试 like that 但正确的as that ...对于你没有从我的代码中超越的事情,我无能为力。 ..
  • 我当然会将它调整为我的变量名;)
  • 我不明白为什么 'clearTimeout' 似乎有效,但 Timeout 一直运行到 'times' = 0
猜你喜欢
  • 2018-01-20
  • 2022-09-27
  • 2020-07-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-13
  • 1970-01-01
  • 2019-10-01
相关资源
最近更新 更多