Reputation: 49
I have the following JS code that shows a countdown timer that should start at the minute 00 of every hour and ends at the minute 10.
@php
$dt = date('Y/m/d H:i:s');
@endphp
<script>
var countDownDate = new Date("Jan 5, 2100 23:10:00").getTime();
var now = new Date("<?php echo $dt; ?>").getTime();
var x = setInterval(function() {
now+= 1000
var distance = countDownDate - now;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timer10").innerHTML =
minutes + "m " + seconds + "s ";
}, 1000);
It is working fine, except that it doesn't stop at 00:00 , and it resets the timer starting again from 59:59. What should I add to stop the timer at 00:00 ?
Upvotes: 1
Views: 34
Reputation: 8650
You are never clearing your interval. You need to call the clearInterval
function.
@php
$dt = date('Y/m/d H:i:s');
@endphp
<script>
var countDownDate = new Date("Jan 5, 2100 23:10:00").getTime();
var now = new Date("<?php echo $dt; ?>").getTime();
var x = setInterval(function() {
now+= 1000
var distance = countDownDate - now;
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
document.getElementById("timer10").innerHTML =
minutes + "m " + seconds + "s ";
if(minutes === 0 && seconds === 0) {
clearInterval(x);
// the interval will stop at this point.
}
}, 1000);
Upvotes: 1