Search code examples
javascripthtmlvariablessetintervalvar

setInterval not updating with variable


When I run the code it only intervals at the initial variable I created "2000". When i click on the button it doesn't change the interval to "50". Does anyone know why?

<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>

This isn't the OG code, more a simplified version of it.


Solution

  • The interval was already set with the 2s, if you change the variable after that, it won't make any difference.

    I recommend you do this:

    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);
    }