我正在尝试构建一个http://codepen.io/GeoffStorbeck/full/RPbGxZ/这样的Pomodoro时钟。秒的值随机变为NaN,然后在开始“中断”后恢复正常。
$('#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);
});
这是指向Codepen的链接http://codepen.io/ibrahimjarif/pen/wMKJWN
如何解决NaN问题?有没有更好的方法来实现这一目标?
该代码以$('#circle a').trigger("click"); //Start timer for break
递归方式调用最初执行的函数。当原始计时器正在进行时,此调用将启动一个新计时器。
执行新计时器时seconds
,原始计时器的值转到该值NaN
。second
由于有两个计时器,因此有两个值。seconds
原始计时器中的值导致出现无法解释的NaN
。
注意:两个计时器一直在同时运行。
最简单的解决方法是在启动新计时器之前先停止当前计时器。
这是更新的代码
$('#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);
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句