javascript - 为什么“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);
}
})
})
有什么理由为什么使用的“clearTimeout()”socket.on('Answered Question', function () {
不起作用?
解决方案
在您的代码中,由于 Timeout 的设置是由事件触发的,因此可能会在未设置clearTimeout
的情况下调用 get 。gameTime
也clearTimeout
被事件触发,如果该事件未触发,则不会清除超时。
问题可能在于您的事件的来源。它们在哪里或何时被触发?
你也可以测试你的if
陈述。console.log
在调用之前放一个clearTimeout
,看看它是否在你想要的时候运行。
推荐阅读
- sitecore - Sitecore 的逻辑应用连接器
- c# - 如何将谓词表达式转换为 SQL Where 子句
- identityserver4 - 使用 IdentityServer4 通过 API 进行用户身份验证
- angular - 如何在 Angular 8 中刷新状态?
- qt - Qt 将来自多个发送者的信号映射到单个插槽
- neo4j - Neo4j Cypher 仅返回计数大于 1 的行
- pdf - 使用 VB 脚本将 Excel 工作簿中的活动工作表保存为 PDF 文件
- jira - JIRA - 当所有状态都可以进入特定状态时,删除到相同状态的转换
- rstudio - R-Studio - 与 Teradata 的连接不起作用
- installation - 为什么我的非常简单的 .exe 在任何地方都被标记为危险?