服务器上有一个计时器,当它启动时,就开始倒计时,但是当用户离开页面时,计时器继续运行,并在用户不再在页面上时触发。如何在用户离开页面之前或已经离开时停止此计时器?
//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()
,但它们对已经离开页面的当前用户不起作用...它们仅对其他用户触发...
最佳答案
您需要存储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();
});
关于javascript - 当用户断开连接时如何停止服务器上的计时器? (Node.js/socket.io),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45917824/