【问题标题】:Jquery countdown reset timer when function called [closed]调用函数时Jquery倒计时重置计时器[关闭]
【发布时间】:2013-08-18 13:36:58
【问题描述】:

我正在尝试制作一个 jquery 脚本,该脚本在您调用函数时从 20 秒开始倒计时,然后在完成时重置。有没有办法做到这一点?

【问题讨论】:

  • 查看js文档了解setTimeout()函数
  • 请更具体。倒数什么?内部还是可见计数器?应该重置什么?
  • 对不起,是的。在“#div span”内显示一个可见的计数器,计时器完成倒计时后应重置。

标签: javascript jquery timer reset countdown


【解决方案1】:

使用 setInterval 被认为是不好的做法,因此最好像这样使用 setTimeout:

var timer = 20 * 1000;

function loop() {
  if (timer > 0) {
    $('#countdown').html(timer / 1000);
    timer -= 1000;
    setTimeout( loop, 1000 );
  } else {
    timer = 20 * 1000;
    $('#countdown').html(timer / 1000);
  }
}

loop();

【讨论】:

    【解决方案2】:
    (function($){
        /// initialize the variables
        var interval,
            $domElementThatContainsTheCountdown = $('.countdown'),
            count = 20;
        function start() {
            /// if the timer is already running, do nothing
            if(interval) return;
    
            $domElementThatContainsTheCountdown.text(count);
            /// set an interval on 1000ms (= 1 second)
            setInterval(function() {
    
                $domElementThatContainsTheCountdown.text(count);
                count -= 1;
    
                /// if the countdown has finished
                if(count === 0) {
                    /// reset count
                    count = 20;
                    $domElementThatContainsTheCountdown.text(count);
                    /// clear the interval
                    clearInterval(interval);
                }
            }, 1000);
        }
    }(jQuery));
    

    【讨论】:

      【解决方案3】:

      试试这个

      var total = 20
      var counter = 20
      var timer = setInterval(function() { 
         $('#Msg').text(counter--);
         if (counter == -1) {
            //clearInterval(timer);
             $('#Msg').text(total);
             counter=20;
         } 
      }, 1000);
      
      This should work for below html
      <span id="Msg">20</span>
      

      【讨论】:

        【解决方案4】:

        尝试关注

        var timeVar = '', max = 20, starter = 0;
        
        $("#btnStart").on("click",function(){
         timer();
        });
        
        function set (){
            if( max != starter){                        
                $(".timer").text((max).toString());
                max--;
        
                if(max == 0){
                    max = 20;
                }
            }            
        }
        
        function timer(){
            timeVar = setInterval(set,500);          
        }
        

        在这里工作小提琴:http://jsfiddle.net/3KLtc/1/

        希望对你有帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-13
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多