clearinterval 不停止调用 setInterval 函数 - 带有套接字 io 的 nodejs

clearinterval not stopping setInterval function getting called - nodejs with socket io

在客户端我只设置了两个按钮,一个调用 socket.on('start-white-clock') 另一个调用 socket.on('start-black-clock')

这是下棋游戏

我的目标是在黑色计时器启动时停止白色计时器,反之亦然

当我调用 socket.on('start-black-clock') 调用函数 blackClock() 时使用下面的代码,函数启动并开始倒计时 - 记录 blackClockTime: 18000, 17990, 17980 .. ...等等等等

不过当我调用 socket.on('start-white-clock') 时 clearInterval(blackClock);

它不会停止 blackClock() 记录 blackClockTime: 18000, 17990, 17980 ..... 等等 它就好像什么都没发生一样继续运行?

//server.js

const express = require('express'); //Line 1
const app = express(); //Line 2

const http = require('http').Server(app);

const io = require('socket.io')(5000)


var time = 180000





//Whenever someone connects this gets executed
io.on('connection', socket => {

    console.log('A user connected - this is socket.id: ' + socket.id);

    //Whenever someone disconnects this piece of code executed
    socket.on('disconnect', function () {
       console.log('Socket disconnected: ' + socket.id)
    });

    socket.on("join-game", (usersEmail, gameId, pageCalledFrom) => {
        socket.join(gameId)
theGameId = gameId
    })







var blackClockOn = false
  var blackClockTime = 18000
 
function blackClock() {
     blackClockTime = blackClockTime - 10
     console.log("blackClockTime: " + blackClockTime)
}


var theGameId;
var whiteClockTime = 18000
var whiteClockOn = false
function whiteClock() {
    whiteClockTime = whiteClockTime - 10
    console.log("white clock time: " + whiteClockTime)
  
}




//start white 
socket.on('start-white-clock',(usersEmail,currentGameId) => {
    console.log("start white clock called")
    whiteClock() 
     setInterval(whiteClock, 1000);
    clearInterval(blackClock); 

})


    //start black 
    socket.on('start-black-clock',(usersEmail,currentGameId) => {
        console.log("start black clock called")
        blackClock()
        setInterval(blackClock, 1000);
       clearInterval(whiteClock); 
    })

这是因为 clearInterval() 接收一个整数作为参数。这个整数是区间的id,由函数setInterval().
返回 所以你需要在 socket.on() 回调之外定义 2 个变量:
let blackInterval, whiteInterval;
然后

socket.on('start-white-clock',(usersEmail,currentGameId) => {
console.log("start white clock called")
whiteClock() 
whiteInterval = setInterval(whiteClock, 1000);
if(blackInterval) clearInterval(blackInterval);
})

  socket.on('start-black-clock',(usersEmail,currentGameId) => {
    console.log("start black clock called")
    blackClock()
    blackInterval = setInterval(blackClock, 1000);
// conditional not needed here as white always starts so its interval should be defined
   clearInterval(whiteInterval); 
})

试试这个。

const intervalID = setInterval(.....);
clearInterval(intervalID);