setInterval 不更新变量

setInterval not updating with variable

当我 运行 代码时,它仅以我创建的初始变量“2000”为间隔。当我点击按钮时,它不会将间隔更改为“50”。有谁知道为什么?

<html>
    <body>
        <h1 id="pressme"> Press me! </h1>
    </body>

    <script>
    amount = 2000;
    var i = 1;
    document.getElementById("pressme").onclick = function() {
        amount = 50;
    }
        function doSomething() {
            i++;
            console.log("I did something! " + i);
        }
        setInterval(doSomething, amount)
    </script>
</html>

这不是 OG 代码,而是它的简化版本。

间隔已经设置为2s,之后再更改变量,没有任何区别。

我建议你这样做:

let amount = 2000;
let interval = setInterval(doSomething, amount);

var i = 1;
document.getElementById("pressme").onclick = function () {
    clearInterval(interval);
    amount = 50;
    setInterval(doSomething, amount);
}
function doSomething() {
    i++;
    console.log("I did something! " + i);
}

您应该同时使用 setInterval 和 clearInterval。

<html>
    <body>
        <h1 id="pressme"> Press me! </h1>
    </body>

    <script>
        amount = 2000;
        var i = 1;
        var handler
        document.getElementById("pressme").onclick = function() {
            amount = 50;
            clearInterval(handler);
            handler = setInterval(doSomething, amount);
        }
        function doSomething() {
            i++;
            console.log("I did something! " + i);
        }
        handler = setInterval(doSomething, amount);
    </script>

所以当点击按钮时,你应该删除原来的 setInterval 处理程序并重新创建它。