2017-05-23 3 views
0

私は、クライアントがsocket.ioを介して 'createTimer'できるプログラムがあります。その後、サーバーは同じ部屋にあるすべてのクライアントに毎秒1秒を送信します。 Timeoutが最大限の繰り返しに達すると、time = 0なので何かがクライアント側で起こります。しかし、特別な場合、タイムアウトが完了する前にクリアする必要があります。しかし、私はclearTimeoutを呼び出す方法を知らない。私はsetIntervalと同じ問題があります。ここに私のコードです:ソケットイベント経由でsetTimeOutを停止するにはどうすればいいですか?

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 ? 
}) 

私は何か助けに感謝しています!あなたは部屋ごとにタイムアウトを格納することができる、そしてあなたがそれらをクリアすることができ

+0

ので、私はタイムアウトID – mcAngular2

答えて

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 
}) 
+0

にローカル変数を使用することはできません同じ時間で実行されている異なるTimoutsがあり、私はしましたそれだけでそれを試してみました。 'setTimerZero'のconsole.logのために、私はこのイベントが正しく呼ばれているのを見るが、時間はちょうど動いている。 Timoutは停止しません。 – mcAngular2

+0

@ mcAngular2あなたは私のコードから追い抜かれないものについては何もできません... –

+0

私は確かに私の変数名に調整します;) – mcAngular2

関連する問題