简体   繁体   中英

How to use setTimeout with a "do while" loop in Javascript?

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());

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM