Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a setInterval() stop using clearInterval() work?

Well, I am trying to make a setInterval() to stop using clearInterval(), here is the code:

let submitBPMkeeper = document.getElementById("submitBPMkeeper");

function startStopBPMkeeper(sr) {
  let bpmKeepTrack = document.getElementById("bpmSet");
  var test1 = 0;
  var t = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value);

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }
  if (sr == "start") {
    submitBPMkeeper.innerHTML = "Stop";
  } else if (sr == "stop") {
    submitBPMkeeper.innerHTML = "Start";
    clearInterval(t);
  }
}

submitBPMkeeper.addEventListener("click", function() {
  if (submitBPMkeeper.innerHTML == "Start") {
    startStopBPMkeeper("start");
  } else if (submitBPMkeeper.innerHTML == "Stop") {
    startStopBPMkeeper("stop");
  }
});
<div id="bpm">
  <h2>Tempo Keepper:</h2>
  <label for="bpmSet">BPM:</label>
  <input type="number" id="bpmSet" name="bpmSet" style="width:40px;" value="80">
  <button id="submitBPMkeeper">Start</button>
  <p id="baseInput"></p>
  <p id="testInput"></p>
</div>

As you can see you can’t stop the thing from counting up, I would really like it to stop when you press stop.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just define the interval variable in the upper scope.

const submitBPMkeeper = document.getElementById("submitBPMkeeper");
const bpmKeepTrack = document.getElementById("bpmSet");

let interval = null;

function toggleBPMKeeper() {
  let test1 = 0;

  function bpmKTcounter() {
    test1 += 1;
    document.getElementById("testInput").innerHTML = test1;
  }

  if (interval) {
    clearInterval(interval);
    interval = null;
    submitBPMkeeper.innerHTML = "Start";
  } else {
    interval = setInterval(bpmKTcounter, 60000 / bpmKeepTrack.value)
    submitBPMkeeper.innerHTML = "Stop";
  }
}

submitBPMkeeper.onclick = toggleBPMKeeper;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading