Javascript/jquery Countdown Timer With Jsfiddle Example?
Solution 1:
setInterval
returns an identity you can use later to clearInterval
:
var interval = setInterval(function() {
/* snip */
$('span').html(minutes + ':' + seconds);
if (parseInt(minutes, 10) == 0 && parseInt(seconds, 10) == 0)
clearInterval(interval);
}, 1000);
And, to avoid the ever-increasing minutes -- 00000001:42
-- either:
- change
length.minutes
tominutes.length
in your prefix test. - cast the values to Numbers when retrieving --
var minutes = parseInt(timer[0], 10);
-- and just testif (minutes < 10) ...
.
Taking option #2, here's an update: http://jsfiddle.net/BH8q9/
Solution 2:
to check the length of a string, it is not
length.minutes
length.seconds
it is
minutes.length
seconds.length
Solution 3:
Made a few simple changes to your code and it works as you'd like:
setInterval(function() {
var timer = $('span').html();
timer = timer.split(':');
var minutes = timer[0];
var seconds = timer[1];
seconds -= 1;
if (minutes < 0) return;
if (seconds < 0 && minutes != 0) {
minutes -= 1;
seconds = 59;
}
elseif (seconds < 10 && length.seconds != 2) seconds = '0' + seconds;
if ((minutes < 10) && ((minutes+'').length < 2)) minutes = '0' + minutes;
$('span').html(minutes + ':' + seconds);
}, 1000);
I moved the if ((minutes < 10).... line down to happen after the minutes -= 1; otherwise at 9:59, you won't get the extra 0. Also length.minutes
is the wrong way around, it'd need to be minutes.length
-- but to make sure it's being treated as a string (which has a length, whereas a number doesn't), I added a blank string to it and then took the length of that.. This is what ((minutes+'').length < 2
does (checks that you have the leading zero).. This is really the best way to accomplish it, but it's the closest to your existing code.
Solution 4:
I understand that an answer has already being accepted but would like to throw in my 2c: I like to avoid extra coding whenever possible. Using Jonathan Lonowski's approach, I would improve it like:
var interval = setInterval(function() {
var timer = $('span').html().split(':');
//by parsing integer, I avoid all extra string processingvar minutes = parseInt(timer[0],10);
var seconds = parseInt(timer[1],10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) clearInterval(interval);
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' + seconds : seconds;
minutes = (minutes < 10) ? '0' + minutes : minutes;
$('span').html(minutes + ':' + seconds);
}, 1000);
Post a Comment for "Javascript/jquery Countdown Timer With Jsfiddle Example?"