Momentjs和倒数计时器 [英] Momentjs and countdown timer
问题描述
我发现Momentjs库非常酷,但是我找不到关于如何完成一些简单任务的文档. 我正在尝试构建一个倒数计时器,我猜我应该使用duration对象,但是我不太了解(可能由于英语不是我的母语).无论如何,这就是我想要的:
I found the Momentjs library which is pretty cool, however I don't find the documentation to be very clear on how to achieve some simple tasks. I'm trying to build a countdown timer and I'm guessing I should use the duration object, but I don't quite understand how (maybe due to the fact that English isn't my first language). Anyways this is what I want:
var time = 7200;
var duration = moment.duration('seconds',time);
setInterval(function(){
//show how many hours, minutes and secods are left
$('.countdown').text(duration.format('h:mm:ss'));
//this doesn't work because there's no method format for the duration object.
},1000);
因此它应该每秒显示一次:
So everysecond it should display:
02:00:00
01:59:59
01:59:58
01:59:57
...
00:00:00
如何使用Momentjs库实现此结果? 谢谢!
How would I achieve this result with the Momentjs library? Thanks!
推荐答案
duration
对象表示一个静态周期,并且不会随着时间的流逝而增加/减少.因此,如果要减少它,则必须自己进行操作,例如创建一种秒计数器或每次重新创建duration
对象.这是第二个选项的代码:
duration
object represents a static period, and it does not increase/decrease with the flow of time. So if you what to decrease it you have to do it yourself, for example creating a kind of a seconds counter or recreating duration
object every time. Here is the code for the second option:
var time = 7200;
var duration = moment.duration(time * 1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
//show how many hours, minutes and seconds are left
$('.countdown').text(moment(duration.asMilliseconds()).format('h:mm:ss'));
}, interval);
这篇关于Momentjs和倒数计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!