-1

I'm trying to make a 30 second countdown on a span element (#thirty) that will be started on click of another element (#start). It doesn't seem to work. I would appreciate your help.

var countdown = function() {
  setTimeout(function() {
    var i = 30;
    do {
      $("#thirty").text(i);
      i--;
    } while (i > 0);
  }, 1000);
}

$("#start-timer").click(countdown());
  • 1
    `$("#start-timer").click(countdown);` – Rajaprabhu Aravindasamy Apr 06 '16 at 19:00
  • You should use a timer. Take a look at this post: http://stackoverflow.com/questions/20618355/the-simplest-possible-javascript-countdown-timer – Sparrow Apr 06 '16 at 19:03
  • 1
    In addition to @Raj's comment, use `setInterval()`, put `var i = 30` outside the callback, get rid of the `do/while` loop, and `clearInterval(interavalId)` when `i === 0`. –  Apr 06 '16 at 19:03

1 Answers1

-1

use this :

var i = 30;
var countdown = function() {
  var timeout_ = setInterval(function() {
      $("#thirty").text(i);
      i--;
      if(i==0){
         i = 30;
         clearInterval(timeout_);
      }
  }, 1000);
}

$("#start-timer").click(countdown);
Sandeep
  • 1,461
  • 13
  • 26