如何解决为什么“clearTimeout”在这种情况下不起作用?
我在使用代码中的“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()”是否有任何原因不起作用?
解决方法
在您的代码中,由于 Timeout 的设置是由事件触发的,因此可能会发生 clearTimeout
get 在未设置 gameTime
的情况下被调用。此外,clearTimeout
是由一个事件触发的,如果该事件没有触发,则不会清除超时。
问题可能在于您的事件的来源。它们在何处或何时被触发?
您还可以测试您的 if
语句。在调用 console.log
之前放置一个 clearTimeout
,看看它是否在您想要的时候运行。
clearTimeout()
没有停止之前启动的 gameTimer
的可能原因:
- 您认为的
socket.on('Answered Question',...)
事件并未发生。要么永远不会发生,要么发生得太快了。 - 条件
if (answeredPlayers.get(playerData[socket.id].room) == (roomMap.get(playerData[socket.id].room)).length)
没有被满足或抛出,因此您永远不会到达clearTimeout()
。 - 在停止一个给定用户之前,您为给定用户启动了多个
gameTimer
,因此第二个会覆盖第一个的计时器,然后您永远不会停止第一个。 - 您的用户离开网页或点击刷新,并且由于您没有显示对
disconnect
事件的侦听,因此gameTimer
一直在运行,永远不会停止。仅供参考,无论这是否是您当前正在查看的问题的原因,都应该得到解决。 - 由于每个 socket.io 连接都有自己的
gameTimer
,您只是对它是否停止感到困惑,也许一个gameTimer
正在停止而您只是被愚弄了事实上,还有其他人也在运行,属于不同的连接。
仅供参考,您可以通过适当的 console.log()
语句确定这些是否是原因,然后研究日志。这些时间敏感、事件驱动的问题通常可以通过详细的日志记录来解决,然后研究日志以确切了解代码中发生了什么和没有发生了什么以及以什么顺序发生。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。