Make countdown start after button is clicked

Lauren picture Lauren · Feb 10, 2014 · Viewed 25.8k times · Source

I'm creating a kid's game with a timer countdown that starts after the user clicks a button.

The code I'm using initiates the countdown without a problem, but I'd like the countdown to start only after the button is clicked.

Here is my code:

window.onload = function(){
(function(){
  var counter = 5;
  setInterval(function() {
    counter--;
    if (counter >= 0) {
      span = document.getElementById("count");
      span.innerHTML = counter;
    }
    if (counter === 0) {
        alert('sorry, out of time');
        clearInterval(counter);
    }
  }, 1000);
})();
}

JSFiddle

Thank you! Lauren

Answer

Sandy picture Sandy · Feb 10, 2014

Use click event of action link with id= "startClock"

$("#startClock").click( function(){
   var counter = 5;
   setInterval(function() {
     counter--;
      if (counter >= 0) {
         span = document.getElementById("count");
         span.innerHTML = counter;
      }
      if (counter === 0) {
         alert('sorry, out of time');
         clearInterval(counter);
       }
     }, 1000);
});