setInterval -没有按照预期的倒计时计时工作

setInterval - not working as expected with countdown timing

本文关键字:倒计时 工作 setInterval      更新时间:2023-09-26
function countdown() {
        setInterval(function() {
            seconds = seconds - 1;
            if(seconds < 1) {
                endGame();
            }
            else {
                if(seconds < 60) {
                    //...
                }
                $('.Timer').text(seconds);      
            }
        }, 1000);
    }

当达到0时调用end game函数。
结束游戏功能就是通过重启按钮重新开始游戏。

如果我按下重启按钮,秒现在一个接一个地减少。

function reset() {
        seconds = 60;           
    }

第一次运行良好。每秒减少一秒。但是在几次重启之后,秒数会很快减少。在五到十秒内达到零。

function startGame() {
        reset();            
        countdown();
        $('.start-button').hide();
    }   
function endGame() {
        $('.start-button').show();
    }

一旦倒计时结束,您需要清除计时器,否则将会有多个计时器实例运行,导致上述行为

function countdown() {
    var interval = setInterval(function () {
        seconds = seconds - 1;
        if (seconds < 1) {
            clearInterval(interval);
            endGame();
        } else {
            if (seconds < 60) {
                //...
            }
            $('.Timer').text(seconds);
        }
    }, 1000);
}