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);
}
}
}
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.
You put your setInterval inside a loop (and other things).
No need to separate time in minutes and seconds, just work with seconds and do some math.
Here is a code that works:
var userObj = {
name: "Joe",
sec: 3605
}
function timerCount()
{
var interval = setInterval(function()
{
console.log(getTimeLeft(userObj.sec));
userObj.sec--;
if(userObj.sec == 0)
{
clearInterval(interval);
console.log('NO MORE TIME');
}
}, 1000);
}
function getTimeLeft(sec)
{
var seconds = Math.floor( sec % 60 );
var minutes = Math.floor( (sec / 60) % 60 );
var hours = Math.floor( (sec / 60 / 60) );
return {
'hours' : hours,
'minutes': minutes,
'seconds': seconds
}
}
timerCount();
This is one more approach you could think of:
function timer(min, sec){
if (min === 0 && sec === 0) return;
setTimeout(function(){
console.log(min, sec);
if (min > 0 && sec === 0) timer(min-1, 59);
if (sec > 0) timer(min, sec-1);
}, 1000);
}
You can invoke this timer:
timer(userObj.min, 0)