【问题标题】:Resetting setinterval in JS在JS中重置setinterval
【发布时间】:2013-11-28 12:56:26
【问题描述】:

代码如下:

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 秒并杀死所有过去的实例。目前,当我多次调用时,它会与过去的实例混淆。我做错了什么?

【问题讨论】:

标签: javascript jquery setinterval


【解决方案1】:

你必须在函数外定义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);
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 1970-01-01
    • 2020-11-16
    相关资源
    最近更新 更多