当用户断开连接时如何停止服务器上的计时器?(Node.js/socket.io)

Ang*_*y B 0 javascript timer 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");   
     });
Run Code Online (Sandbox Code Playgroud)

我试图停下clearTimeout()socket.on("disconnect")socket.on("disconnecting") 但它们对已经离开页面的当前用户不起作用...它们只为其他用户触发...

Nem*_*ani 5

您需要存储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();
         });
Run Code Online (Sandbox Code Playgroud)