Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add start button using javascript

Iam trying to create countdown timer. Everytime i reload the page, the timer start directly.. I want to add start button to let the time start after i press the button..

this is my code :

var counter = 30;
var mode = "Workout";
var rounds = 1;

var interval = setInterval(function() {
  counter--;

  if (mode == "Workout" && counter >= 0) {
    id = document.getElementById("count");
    id.innerHTML = "ROUND " + rounds + " <br> " + counter;
  } else {
    id = document.getElementById("count");
    id.innerHTML = "REST " + " <br> " + counter;
  }

  if (counter === 0) {
    if (mode == "Workout") {
      mode = "Rest";
    } else {
      mode = "Workout";
      rounds++;
    }
    id.innerHTML = "FINISHED";
    counter = 30;
    if (rounds == 21) {
      clearInterval(interval);
    }
  }

}, 1000);
<div>
  <h1 id="count"></h1>
</div>

Thanks for your help..

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just wrap your code in a function, and add that to the button as an event listener listening for click events:

document.getElementById('start').addEventListener('click', startCountdown);

function startCountdown() {
  let counter = 30,
    mode = "Workout",
    rounds = 1;
  const interval = setInterval(function() {
    counter--;

    if (mode == "Workout" && counter >= 0) {
      id = document.getElementById("count");
      id.innerHTML = "ROUND " + rounds + " <br> " + counter;
    } else {
      id = document.getElementById("count");
      id.innerHTML = "REST " + " <br> " + counter;
    }

    if (counter === 0) {
      if (mode == "Workout") {
        mode = "Rest";
      } else {
        mode = "Workout";
        rounds++;
      }
      id.innerHTML = "FINISHED";
      counter = 30;
      if (rounds == 21) {
        clearInterval(interval);
      }
    }

  }, 1000);
}
<div>
  <h1 id="count"></h1>
</div>
<button type="button" id="start">Start Countdown</button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading