【发布时间】:2021-08-05 14:49:37
【问题描述】:
在我的代码中使用“clearTimeout()”阻止“gameTimer”计时器运行时遇到问题。我在这里简化了部分代码,只包含必要的细节。
//This runs when someone connects to my website
io.on('connection', function (socket) {
let gameTimer;
//Runs the in-game timer
function questionCountdown() {
gameTimer = setTimeout(function () {
//Reveal if the players' answers are right or wrong
revealAnswer(answeredPlayers, playerData[socket.id].room);
//Start the countdown for the next question
countToNextQuestion(playerData[socket.id].room);
}, 21000)
}
//Starts the game
socket.on('Request Game Start', async function (room) {
questionCountdown();
})
//Runs when a player has answered(ignore the function arguments)
socket.on('Answered Question', function () {
//If all users in the room have answered...
if (answeredPlayers.get(playerData[socket.id].room) == (roomMap.get(playerData[socket.id].room)).length) {
//Stop the count[THE MAIN ISSUE]
clearTimeout(gameTimer);
//Reveal if the players' answers are right or wrong
revealAnswer(answeredPlayers, playerData[socket.id].room);
//Start the countdown for the next question
countToNextQuestion(playerData[socket.id].room);
}
})
})
socket.on('Answered Question', function () {中使用的“clearTimeout()”有什么原因不起作用吗?
【问题讨论】:
-
你有什么问题?请更详细地准确描述发生了什么事件、您观察到发生了什么以及您期望或希望发生什么。
-
另外,请更正代码的缩进,以便我们更容易看到哪些代码在哪些事件处理程序中。
-
您确定有时满足您的 if 条件吗?例如,输入一个 console.log 以确保您正在输入该代码。当计时器已经被清除时是否满足?
-
@jfriend00 我已经缩进了一点。当有人回答问题时,我希望计时器停止。但目前它并没有停止,
标签: javascript node.js sockets timeout