不能使用clearInterval()方法

时间:2017-11-24 23:09:11

标签: javascript

它可能与'计时器'范围有关,但我无法解决问题所在。如果有人知道:)

function startTimer() {

    let time = 0;
    progress.style.width = time + '%';

    let timer = function() {

        setInterval(function() {

            time += 0.5;
            progress.style.width = time + '%';
            if (time >= 100) {
                clearInterval(timer);
            }
        }, 100);
    }
    timer();
}

2 个答案:

答案 0 :(得分:0)

window.clearInterval(intervalId)

稍后

StoreLocalVariable: function (key, value) { localStorage.setItem(key, value); }, GetLocalVariable: function (key) { return localStorage.getItem(key); },

答案 1 :(得分:0)

您需要存储setInterval()的实例才能清除它。您正在将函数传递给clearInterval()

function startTimer() {

    let time = 0;
    progress.style.width = time + '%';
    // declare instance variable
    let intervalTimer;

    let timer = function() {
         // assign instance
         intervalTimer = setInterval(function() {

            time += 0.5;
            progress.style.width = time + '%';
            if (time >= 100) {
                // clear instance
                clearInterval( intervalTimer);
            }
        }, 100);
    }
    timer();
}