【问题标题】:countdown timer using moment.js mm:ss format使用 moment.js mm:ss 格式的倒数计时器
【发布时间】:2015-08-21 13:02:41
【问题描述】:

我正在使用这个moment.js

示例代码如下:

var mytimer= moment().format('00:60');

setInterval(counter,500);

function counter(){
     mytimer--; // its return NaN error
     sym.$("Text").html(mytimer);
}

我怎样才能让它这样倒计时?

00:60 00:59 ... 00:00

提前致谢!

【问题讨论】:

    标签: javascript momentjs


    【解决方案1】:

    在这种情况下,您不需要使用 moment。我觉得它是一个更适合格式化日期的库,而不是计时器。请看我下面的例子。它使用回调,因此您可以重复使用它来做任何事情。

        function MyTimer(callback, val) {
            val = val || 60; 
            var timer=setInterval(function() { 
                callback(val);
                if(val-- <= 0) { 
                    clearInterval(timer); 
                } 
            }, 1000);
        }
        new MyTimer(function(val) {
            var timerMsg = "00:" + (val >= 10 ? val : "0" + val);
            document.getElementById("timer").textContent = timerMsg; 
        });
    &lt;div id="timer"&gt;&lt;/div&gt;

    【讨论】:

      【解决方案2】:

      我知道这不是使用时刻,但是这是您想要的格式

      Check this out.

      http://jsfiddle.net/robbmj/czu6scth/2/

      window.onload = function() {
      
            var display = document.querySelector('#time'),
                timer = new CountDownTimer(5);
      
            timer.onTick(format).onTick(restart).start();
      
            function restart() {
              if (this.expired()) {
                setTimeout(function() { timer.start(); }, 1000);
              }
            }
      
            function format(minutes, seconds) {
              minutes = minutes < 10 ? "0" + minutes : minutes;
              seconds = seconds < 10 ? "0" + seconds : seconds;
              display.textContent = minutes + ':' + seconds;
            }
          };
      

      这将以 00:00 格式显示。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-02-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多