简体   繁体   English

如何在Javascript中使用带有“do while”循环的setTimeout?

[英]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).我正在尝试对将在单击另一个元素 (#start) 时启动的跨度元素 (#thirty) 进行 30 秒倒计时。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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