setInterval 不更新变量

当我运行代码时,它仅在我创建的初始变量“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 代码,而是它的简化版本。


梵蒂冈之花
浏览 61回答 2
2回答

青春有我

您应该将 setInterval 与clearInterval 一起使用。<html>&nbsp; &nbsp; <body>&nbsp; &nbsp; &nbsp; &nbsp; <h1 id="pressme"> Press me! </h1>&nbsp; &nbsp; </body>&nbsp; &nbsp; <script>&nbsp; &nbsp; &nbsp; &nbsp; amount = 2000;&nbsp; &nbsp; &nbsp; &nbsp; var i = 1;&nbsp; &nbsp; &nbsp; &nbsp; var handler&nbsp; &nbsp; &nbsp; &nbsp; document.getElementById("pressme").onclick = function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; amount = 50;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; clearInterval(handler);&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; handler = setInterval(doSomething, amount);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; function doSomething() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; i++;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; console.log("I did something! " + i);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; handler = setInterval(doSomething, amount);&nbsp; &nbsp; </script>因此,当单击按钮时,您应该删除原始的 setInterval 处理程序并重新创建它。

慕的地10843

间隔已经设置为 2 秒,如果之后更改变量,则不会有任何影响。我建议你这样做:let amount = 2000;let interval = setInterval(doSomething, amount);var i = 1;document.getElementById("pressme").onclick = function () {&nbsp; &nbsp; clearInterval(interval);&nbsp; &nbsp; amount = 50;&nbsp; &nbsp; setInterval(doSomething, amount);}function doSomething() {&nbsp; &nbsp; i++;&nbsp; &nbsp; console.log("I did something! " + i);}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5