javascripthtmltogglebuttonclearintervalischecked

Javascript / Toggle / Switch / clearInterval() - not able to clearInterval() when the toggle is switched off


wow, this is my first post! New to programming and coding, this is something of my first projects I work on. I would like to be able to switch a toggle to run a code or to stop it, using the setInterval() for it. But now I am not able to switch it off when selecting the toggle. Tried multiple thing, like break; but not successful so far. Would be great if any of you could point me in the right direction.

Kind regards, Laurens

Code in HTML

<card>
<p>Theft Script ON/OFF</p>
<label class="switch">
<input id="executeTheftScript" type="checkbox" > Toggle me
</label>
</card>

Code in Javascript

function theftToggle(){
    var isChecked = document.getElementById("executeTheftScript").checked;
    if (isChecked) {
        var i = setInterval(function(){
            if (person1.credits === 0) {
                clearInterval(i);
                updateStats();
                console.log("You don't have any credits.");
            } else {
                theft();
                person1.credits--;
                updateStats();
            };
        }, 500);
    } else {
        console.log("Your script is stopped.");
    }
}

document.getElementById("executeTheftScript").addEventListener('click', theftToggle);

Running of the code;

enter image description here


Solution

  • you need addEventListener to the input and it better to set the setInterval variable outside function or make it global so it will not create duplicate setInterval.

    var interval;
    var person1 = {
      credits: 10
    }
     
    // listen the input for checked change
    document.getElementById("executeTheftScript").addEventListener('change', theftToggle);
    
    function theftToggle() {
      var isChecked = document.getElementById("executeTheftScript").checked;
      if (isChecked) {
        interval = setInterval(function() {
          if (person1.credits === 0) {
            clearInterval(interval);
            updateStats();
            console.log("You don't have any credits.");
          } else {
            theft();
            person1.credits--;
            updateStats();
          }
        }, 500);
      } else {
        clearInterval(interval)
        console.log("Your script is stopped.");
      }
    }
    
    function theft() {}
    
    function updateStats() {
      console.log("credits: ", person1.credits);
    }
    <card>
      <p>Theft Script ON/OFF</p>
      <label class="switch">
        <input id="executeTheftScript" type="checkbox"> Toggle me
      </label>
    </card>