首页 > 解决方案 > 为什么“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 () {不起作用?

标签: javascriptnode.jssocketstimeout

解决方案


在您的代码中,由于 Timeout 的设置是由事件触发的,因此可能会在未设置clearTimeout的情况下调用 get 。gameTimeclearTimeout被事件触发,如果该事件未触发,则不会清除超时。

问题可能在于您的事件的来源。它们在哪里或何时被触发?

你也可以测试你的if陈述。console.log在调用之前放一个clearTimeout,看看它是否在你想要的时候运行。


推荐阅读