0
votes

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">&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>
1

1 Answers

1
votes

Your problem is that inside of your VisibleCountDownTimer45s() function, you are redeclaring a locally-scoped variable named xx. Remove the var keyword there, and you'll be assigning the timer to the global xx variable that is accessible to other functions. This is known as a scope issue.

Change: var xx = setInterval(function() {

To: xx = setInterval(function() {

See this:

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

Also worth noting that you can achieve the same result without using a Date object and calculating the elapsed time relative to it.

let timer;

function startTimer(interval) {
  if (timer !== undefined) {
    clearInterval(timer);
  };
  timer = setInterval(function() {
    interval -= 1000
    if (interval <= 0) {
      clearInterval(timer);
      document.getElementById("demo").innerHTML = "";
    } else {
      const seconds = Math.floor(interval / 1000);
      document.getElementById("demo").innerHTML = seconds + "s ";
    }
  }, 1000);
}
<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>
<div class="container">
  <div class="row">
    <div class="col-md-4 text-right"><button class="btn btn-primary" onclick="startTimer(45000)">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(timer)">Stop visible Timer</button></div>
  </div>
</div>