使用Moment.js实现24小时倒计时计时器

3
请帮我实现一个24小时倒计时器,使用moment.js。这是我的代码:
<script>
window.onload = function(e){

var $clock = $('#clock'),

duration1 = moment.duration({
    'seconds': 30,
    'hour': 0,
    'minutes': 0,
    'days':0
});
duration2 = moment.duration({
    'seconds': 60,
    'hour': 0,
    'minutes': 0,
    'days':0
});

diff=duration2-duration1;
duration=moment.duration(diff, 'milliseconds');


interval = 1000;
setInterval(function(){    
    duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');            
    $('#clock').text(duration.days() + 'd:' + duration.hours()+ 'h:' + duration.minutes()+ 'm:' + duration.seconds() + 's');    
 }, interval);
</script>

问题是每当我刷新页面时,计时器也会刷新。如何解决这个问题?如果有更好的实现方法,请分享。

谢谢


你可以选择一个计时器从页面加载开始倒计时24小时,或者你可以向一个预定的时间点倒计时;听起来你想要后者。如果是这样,你需要至少在代码中有那个时间戳。 - Aron
你好,Aron。我该如何创建时间戳以便从当前时间生成24小时的时间戳? - James Blare
看看我的回答。它回答了你的问题吗? - Aron
3个回答

5
这是我的做法:
// create the timestamp here. I use the end of the day here as an example
const end = moment().endOf('day'); 

setInterval(function() {
    const timeLeft = moment(end.diff(moment())); // get difference between now and timestamp
    const formatted = timeLeft.format('HH:mm:ss'); // make pretty

    console.log(formatted); // or do your jQuery stuff here
}, 1000);

每秒钟会打印出一个时间戳,类似于这样:
09:49:25 
09:49:24 
09:49:23 
09:49:22 
...

2
从这里我可以设置我想要的时间戳并从中倒计时。谢谢Aron。 - James Blare
1
绝对会这样做。 - James Blare
在我的情况下,diff 没有以正确的方式工作。因此,我尝试了几种解决方案并作为回复添加了进去。 - Juneyoung Oh

2

我觉得估算剩余时间的逻辑可能存在一个 bug。这个语句是 const timeLeft = moment(end.diff(moment(), true))

我发现的是...

const end = moment().endOf('day');                      // Mon Oct 22 2018 23:59:59 GMT+0900
const now = moment();                                   // Mon Oct 22 2018 14:38:30 GMT+0900
const timeLeft = moment(end.diff(moment(), true));      // diff = 33689322
const formatted = timeLeft.format('HH:mm:ss');          // 18:21:29

当你使用Date对象进行计算时,它会返回9小时左右的时间。我认为使用不同的初始化moment对象导致了这个bug。

这是我的解决方案的最终形式。

const end = moment().endOf('day');

console.log('End date', moment(), end, end.diff(moment()), moment().diff(end));
const timeLeft = moment.duration(end.diff(moment()));       // Use duration

const formatted =
  this.checkDigit(timeLeft.hours()) + ':'
  + this.checkDigit(timeLeft.minutes()) + ':'
  + this.checkDigit(timeLeft.seconds());        // checkDigit is a function which adds 0 to the numbers under 10

主要区别在于duration函数。当然,这可能是版本差异导致的。

0
你可以使用 localStorage 来保存原始时间戳。另一种选择是将其保存在服务器上(数据库?)。无论哪种方式,如果刷新页面,仍然会倒计时到相同的时间。

你好 Harry,如果我在服务器上保存时间戳,那么如何为用户分配唯一的计时器(假设他们点击了一个按钮)? - James Blare
回到将某种 ID 保存在客户端的 localStorage(或 cookie)中。 - Harry Pehkonen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接