将分钟转换为秒并尝试每秒向上或向下计数

时间:2017-06-23 07:00:36

标签: javascript momentjs

我正在使用MomentJS + Moment Duration Format将时间(值以分钟为单位)转换为秒,然后我试图像计时器那样每秒向上或向下计数。

我在下面做了一个例子,它能够将时间从几分钟转换为几秒钟,并在几分钟内显示计时器,但是,我无法计算

我不确定MomentJS是否能够使用额外插件(Moment Duration Format)执行此操作。

有什么想法吗?

var tar = $('span');

test(tar, 3)

function test(tar, time) {
  setInterval(function() {
    var minsToSecs = moment.duration(time, 'minutes').asSeconds(),
      timeInSeconds = minsToSecs++,
      formattedDur = moment("1900-01-01 00:00:00").add(timeInSeconds, 'seconds').format("HH:mm:ss");

    tar.html(formattedDur);
  }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

<span></span>

3 个答案:

答案 0 :(得分:1)

在这里。

var tar = $('span');
var instant = moment("1900-01-01 00:00:00");

test(tar, 3)

function test(tar, time) {
    var minsToSecs = moment.duration(time, 'minutes').asSeconds(),
      timeInSeconds = minsToSecs;

  setInterval(function() {
      formattedDur = instant.add(timeInSeconds, 'seconds').format("HH:mm:ss");
      timeInSeconds= 1;

    tar.html(formattedDur);
  }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

<span></span>

答案 1 :(得分:0)

扩展我上面的评论...

var tar = $('span');
var instant = moment("1900-01-01 00:00:00");

test(tar, 3)

function test(tar, time) {
    var minsToSecs = moment.duration(time, 'minutes').asSeconds(),
      timeInSeconds = minsToSecs;

  setInterval(function() {
      formattedDur = instant.add(timeInSeconds, 'seconds').format("HH:mm:ss");
      timeInSeconds= 1;

    tar.html(formattedDur);
  }, 1000);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

<span></span>

答案 2 :(得分:0)

每次迭代,您将3分钟转换为秒,然后以秒为单位指定时间。然后你添加一个minsToSeconds,此时不再使用。然后将TimeInSeconds添加到模板中。因为时间永远不会改变,所有这些其他值都是基于的,所以你的时间永远不会改变。找到一种方法来增加'时间',这将使你的时钟去。