I created a simple countdown timer to display a count down of 45 seconds. I am trying to control this timer by two buttons using the JavaScript onclick function. One button will start the timer and one will stop it. I am able to start the time and get it to display on screen, but not able to stop it. I found the time script online and modified it to show only the seconds.
I tried to create a global id ("var xx;" in this case) to clear the interval but did not work. I am not sure what is missing. Here is the important parts of my code using Bootstrap 4.
// create a global variable to reset the interval later
var xx;
// Visible Coundown 45s function
function VisibleCountDownTimer45s() {
// reset internval if it is already in defined.
if(xx != undefined) {
clearInterval(xx)
};
// Set the date we're counting down to
var countDownDate = new Date().getTime() + 45000;
// Update the count down every 1 second
var xx = setInterval(function() {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// console.log (distance);
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = seconds + "s ";
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(xx);
document.getElementById("demo").innerHTML = "";
}
}, 1000);
}
<!-- timer display box -->
<div class="container">
<div class="row mb-3">
<div class="col-md-4"> </div>
<div class="col-md-4 text-center pb-3" id="demo"><span class="border border-secondary p-2">show timer here</span></div>
<div class="col-md4"> </div>
</div>
</div>
<!-- control buttons -->
<div class="container">
<div class="row">
<div class="col-md-4 text-right"><button class="btn btn-primary" onclick="VisibleCountDownTimer45s()">Start visible Timer</button></div>
<div class="col-md-4 text-center" id="Counter"><p> </p></div>
<div class="col-md4 text-left"><button class="btn btn-primary" onclick="clearInterval(xx)">Stop visible Timer</button></div>
</div>
</div>