Quantcast
Channel: Active questions tagged html - Stack Overflow
Viewing all articles
Browse latest Browse all 80408

Troubleshooting Stopping a Countdown Timer - No sure how to proceed from here

$
0
0

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. If anybody can help me with this, I will greatly appreciate it. Here is the important parts of my code using bootstrap 4.

<-- timer display box -->

<div class="container">
<div class="row mb-3">
<div class="col-md-4">&nbsp;</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">&nbsp;</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>&nbsp;</p></div>
<div class="col-md4 text-left"><button class="btn btn-primary" onclick="clearInterval(xx)">Stop visible Timer</button></div>    
</div>
</div>

<script>
// 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);
            }    
</script>

Viewing all articles
Browse latest Browse all 80408

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>