Home > Enterprise >  Resetting the setInterval puts it in a multiple loop interval instead
Resetting the setInterval puts it in a multiple loop interval instead

Time:09-25

In this JSfiddle, I have a code where if you click on the button, it automatically creates another set interval within the old one,

I have clearInterval but for some reason, it's not working

(Try clicking on the timer button multiple times)

<span>LIVE: Election results will refresh in <span id="time">2:00</span> minutes.</span>
<input type="button" value="Timer" id="btn">
<script>
$("#btn").on('click', function() {
  var twoMinutes = 60 * 2,
    display = document.querySelector('#time');

  startTimer(twoMinutes, display);
});

function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  var interval;
  clearInterval(interval);
  interval = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ?  minutes : minutes;
    seconds = seconds < 10 ? "0"   seconds : seconds;

    display.textContent = minutes   ":"   seconds;
    if (--timer < 0) {
      timer = duration;
      LoadCandidatesCharts(true);
    }
  }, 1000);

} </script>

enter link description here

CodePudding user response:

Problem is because you're calling the interval var within the function scope, while you should be declaring it on a global scope, try this

var interval; // global var
function startTimer(duration, display) {
  var timer = duration,
    minutes, seconds;
  
  clearInterval(interval);
  interval = setInterval(function() {
    minutes = parseInt(timer / 60, 10)
    seconds = parseInt(timer % 60, 10);

    minutes = minutes < 10 ?  minutes : minutes;
    seconds = seconds < 10 ? "0"   seconds : seconds;

    display.textContent = minutes   ":"   seconds;
    if (--timer < 0) {
      timer = duration;
      LoadCandidatesCharts(true);
    }
  }, 1000);

}
  • Related