简体   繁体   中英

clearInterval not woking and weirdness in an if statement

I'm making a time object but am experiencing something weird with my clearInterval but really the function in general. The relevant code looks like:

var timer = {
timerStarted: false,

startTimer: function(){
  var howMuchTime = parseInt($('#timer-button-number').text());
  var timesUpAt = Date.now() + howMuchTime*60*1000;
  var start = new Date().getTime();
  var milseccount = timesUpAt - start;

  function sectimer(){
    var remaining = Math.floor(milseccount - (new Date().getTime() - 
    start));
    if (remaining <= 0) {
      clearInterval(x);
    }
    var minutes = Math.floor((remaining % (1000*60*60)) / (1000*60));
    var seconds = Math.floor((remaining % (1000*60)) / 1000);
    //display results
    $('#timer-button-number').text(minutes + 'm ' + seconds + 's');
  }

  var x = null;
  if (!timer.timerStarted) {
    x = setInterval(sectimer, 100);
    timer.timerStarted = true;
  } else if (timer.timerStarted){
    clearInterval(x);
    timer.timeStarted = false;
    console.log(timer.timeStarted);
  }
 }

}

So on the button click the timer starts, the value of timer.timeStarted switchs to true. But when the button is clicked again the interval doesen't clear. The timer.timeStarted switches to false but when the button is clicked again the second part of the if statment continues to be executed (all but the clearInterval part), as if the if statement doesn't dictate that the interval should be started again (even though it never actually stopped). Could someone help?

Your nulling your variable X every time it runs...

try moving it to the beginning like this:

x = null;
var timer = {
timerStarted: false,

startTimer: function(){
var howMuchTime = parseInt($('#timer-button-number').text());
var timesUpAt = Date.now() + howMuchTime*60*1000;
var start = new Date().getTime();
var milseccount = timesUpAt - start;

function sectimer(){
var remaining = Math.floor(milseccount - (new Date().getTime() - 
start));
if (remaining <= 0) {
  clearInterval(x);
}
var minutes = Math.floor((remaining % (1000*60*60)) / (1000*60));
var seconds = Math.floor((remaining % (1000*60)) / 1000);
//display results
$('#timer-button-number').text(minutes + 'm ' + seconds + 's');
}


if (!timer.timerStarted) {
  x = setInterval(sectimer, 100);
  timer.timerStarted = true;
} else if (timer.timerStarted){
  clearInterval(x);
  timer.timeStarted = false;
  console.log(timer.timeStarted);
}
}

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM