I'm trying to build a Pomodoro clock like http://codepen.io/GeoffStorbeck/full/RPbGxZ/. The value of seconds goes to NaN randomly and then returns to normal after starting 'break'.
$('#circle a').click(function() {
var timer = $('.time > span').html();
timer = timer.split(':');
var minutes = timer[0]; //Value of minutes
var seconds = timer[1]; //Value of seconds
var settimer = setInterval(function() {
seconds -= 1;
console.log(seconds);
if (seconds < 0 && minutes != 0) {
minutes -= 1;
minutes = String(minutes);
seconds = 59;
} else if (seconds < 10 && seconds.length != 2)
seconds = '0' + seconds;
if (minutes < 10 && minutes.length < 2)
minutes = '0' + minutes;
$('.time > span').html(minutes + ':' + seconds);
//Start break when session is completed
if (minutes == 0 && seconds == 0) {
$('.upper').find('h1').text('BREAK');
var time = $('#break').find('span').text();
$('.time > span').html('0' + time + ':00');
$('#circle a').trigger("click"); //Start timer for break
}
}, 1000);
});
Here's the link to the codepen http://codepen.io/ibrahimjarif/pen/wMKJWN
How do I fix the NaN issue? And is there any better way to implement this?
The code $('#circle a').trigger("click"); //Start timer for break
recursively calls the function that was executing originally. This call starts a new timer while the original one was in progress.
The seconds
value for the original timer went to NaN
when the new timer was executing. There were two values for second
due to two timers. The value of seconds
in the original timer caused the unexplained appearance of NaN
.
NOTE: Both the timers were running simultaneously all the time.
The simplest fix was to stop the current timer before starting a new one.
Here's the updated code
$('#circle a').click(function() {
var timer = $('.time > span').html().split(':');;
var minutes = Number(timer[0]),
seconds = Number(timer[1]);
var settimer = setInterval(function() {
seconds -= 1;
if (seconds < 0 && minutes != 0) {
minutes -= 1;
seconds = 59;
} else if (seconds < 10 && seconds.length != 2)
seconds = '0' + seconds;
if (minutes < 10 && minutes.toString().length < 2)
minutes = '0' + minutes;
$('.time > span').html(minutes + ':' + seconds);
if (minutes == 0 && seconds == 0) {
clearInterval(settimer); //Stop the current timer
var upper_text = $('.upper').find('h1');
var time;
if (upper_text.text() == 'BREAK') {
upper_text.text('Session');
time = $('#session').find('span').text();
} else {
upper_text.text('BREAK');
time = $('#break').find('span').text();
}
$('.time > span').html(time + ':00');
$('#circle a').trigger("click"); //Start new timer
}
}, 1000);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With