Trip1 Trip1 - 6 months ago 17
Javascript Question

Why is setInterval making infinite loops

I'm trying to set a timer so it display the seconds and min left of an user and I'm using setInterval to get the seconds and if there are 60 seconds it will reduce 1 min from the user.
The thing is that I'm getting infinite foorloops every time i try to do it.

something like

var userObj = {
name: "",
min: 0,
sec:0
}

function timerCount() {
while (userObj.sec !== 0) {
console.log(userObj.min)
if (userObj.sec == 0) {
setInterval(function() {
userObj.min--;
userObj.sec = 59
}, 1000);
}
while(userObj.sec !== 0) {
setInterval(function() {
console.log(userObj.sec)
userObj.sec--;
}, 1000);
}
}
}

Answer
var userObj = {
    name: "",
    min: 0,
    sec:5
}

function timerCount() {

  if(userObj.min === 0 && userObj.sec === 0) {
    return;
  }

  if (userObj.sec === 0) {
    userObj.min--;
      userObj.sec = 59     
    }     
  userObj.sec--;  


  setTimeout(timerCount, 1000)
}

timerCount()

With little effort we can remove those while loops that are causing the issue. We also want to check for the minutes and seconds equalling 0 so we know when to end our timer.