0

代码如下所示:

function startTimer(counter) {
    var interval = setInterval(function () {
        counter--;
        $('#timer').html(counter);
        // Display 'counter' wherever you want to display it.
        if (counter == 0) {
            clearInterval(interval);
            $('#question').html("Time ended");
            setTimeout(function () {
                window.location.href = "/";
            }, 5000);
            return false;
        }
    }, 1000);
}

我想要做的是,当我多次调用此函数时,每次将计时器重置为 30 秒并杀死所有过去的实例。目前,当我多次调用时,它会与过去的实例混淆。我究竟做错了什么?

4

1 回答 1

0

您必须在函数外部定义 var 区间:

   var interval;
    function startTimer(counter) {
        interval = setInterval(function () {
            counter--;
            $('#timer').html(counter);
            // Display 'counter' wherever you want to display it.
            if (counter == 0) {
                clearInterval(interval);
                $('#question').html("Time ended");
                setTimeout(function () {
                    window.location.href = "/";
                }, 5000);
                return false;
            }
        }, 1000);
    }
于 2013-11-15T08:10:06.637 回答