2017-08-28 148 views
0

在服務器上有一個定時器,當它啓動時,開始倒計時,但當用戶離開頁面時,定時器繼續運行並在用戶不再開啓時觸發這一頁。如何在用戶離開頁面或已經離開頁面之前停止該計時器?如何在用戶斷開連接時停止服務器上的定時器? (Node.js/socket.io)

//Timer function 
    function startTimer() { 
     console.log("Timer statrted!"); 
     var countdown = 15000; 
     setTimeout(function() { 
      console.log("Timer done!"); 
     }, 15000); 
    } 

    socket.on("get data", function() { 
     io.to(room_name).emit("data"); 
     //call timer 
     startTimer(); //"Timer started!", "user disconnected", (after 15s) "Timer done!" 
    }); 



    socket.on("disconnect" ,function(){ 
     console.log("user disconnected"); 
    }); 

我試着在socket.on("disconnect")socket.on("disconnecting")停止clearTimeout()但他們不上誰已經離開該頁面當前用戶的工作......他們只是引發了另一個用戶...

+0

你需要存儲的timerId並使用clearTimeout相同 – Nemani

回答

2

您需要存儲的timerId並使用相同的clearTimeout

var socketTimer; 
    function startTimer() { 
      console.log("Timer statrted!"); 
      var countdown = 15000; 
      socketTimer = setTimeout(function() { 
       console.log("Timer done!"); 
      }, 15000); 
     } 

    function stopTimer(){ 
     clearTimeout(socketTimer); 
    } 
     socket.on("get data", function() { 
      io.to(room_name).emit("data"); 
      //call timer 
      startTimer(); //"Timer started!", "user disconnected", (after 15s) "Timer done!" 
     }); 



     socket.on("disconnect" ,function(){ 
      console.log("user disconnected"); 
      stopTimer(); 
     }); 
相關問題