为什么'clearTimeout'在这种情况下不起作用?



我在代码中阻止"游戏计时器"使用"clearTimeout()"运行时遇到问题。我在这里简化了部分代码,只包含必要的细节。


//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()"不起作用?

clearTimeout()不会停止先前启动的gameTimer的可能原因:

  1. socket.on('Answered Question', ...)事件并没有在您认为的那样发生。 要么它永远不会发生,要么发生得太早。
  2. 条件if (answeredPlayers.get(playerData[socket.id].room) == (roomMap.get(playerData[socket.id].room)).length)没有得到满足或抛出,因此你永远无法到达clearTimeout()
  3. 在停止一个用户之前,您为给定用户启动了多个gameTimer,因此第二个会覆盖第一个计时器,然后永远不会停止第一个计时器。
  4. 您的用户离开网页或点击刷新,并且由于您不显示侦听disconnect事件,因此您将运行一个永远无法停止的gameTimer。 仅供参考,无论它是否是您正在查看的当前问题的原因,都应该解决此问题。
  5. 由于每个 socket.io 连接都有自己的gameTimer,您只是对它是否停止感到困惑,也许一个gameTimer被停止,而您只是被以下事实所愚弄:还有其他正在运行属于不同连接。

仅供参考,您可以通过适当的console.log()语句确定其中是否有任何原因,然后研究日志。 这些对时序敏感的事件驱动问题通常通过详细的日志记录来解决,然后研究日志,以准确了解代码中发生了什么,没有发生什么,以及以什么顺序。

在您的代码中,由于超时的设置是由事件触发的,因此可能会发生在没有设置gameTime的情况下调用clearTimeoutget。此外,clearTimeout是由事件触发的,如果该事件未触发,则不会清除超时。

问题可能出在事件的来源上。它们在何时何地被触发?

您还可以测试您的if语句。在调用clearTimeout之前放一个console.log,看看它是否在您想要时运行。

最新更新