I am working on Jquery and i am displaying "countdown timer" using jquery and right now i am showing timer of "1 minute 25 seconds" but after this time i am getting "-1 minutes : 59 seconds", There should be display "0 minutes 0 seconds",how can i do this? Here is my current code
<script>
var timer2 = "0:25";
var interval = setInterval(function() {
var timer = timer2.split(':');
//by parsing integer, I avoid all extra string processing
var 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) ? minutes : minutes;
$('.countdown').html(minutes ' minutes : ' seconds ' seconds');
timer2 = minutes ':' seconds;
}, 1000);
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ></div>
CodePudding user response:
You're missing a return
statement before writign the result on screen.
var timer2 = "0:5";
var interval = setInterval(function() {
var timer = timer2.split(':');
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes < 0) {
clearInterval(interval);
return; /* ADD THIS */
}
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes ' minutes : ' seconds ' seconds');
timer2 = minutes ':' seconds;
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ></div>
otherwise (without the return
) make sure your seconds
are also at 0
var timer2 = "0:5";
var interval = setInterval(function() {
var timer = timer2.split(':');
var minutes = parseInt(timer[0], 10);
var seconds = parseInt(timer[1], 10);
--seconds;
minutes = (seconds < 0) ? --minutes : minutes;
if (minutes === 0 && seconds === 0) clearInterval(interval); /* EDIT */
seconds = (seconds < 0) ? 59 : seconds;
seconds = (seconds < 10) ? '0' seconds : seconds;
//minutes = (minutes < 10) ? minutes : minutes;
$('.countdown').html(minutes ' minutes : ' seconds ' seconds');
timer2 = minutes ':' seconds;
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div ></div>