2017-03-16 2044 views
0

请在moment.js中实施24小时倒数计时器,我需要帮助。这里是我的代码:使用Moment.js实现24小时倒数计时器

<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> 

问题是我刷新页面的任何时候定时器刷新也。我如何解决这个问题。如果有更好的方法来实现这一点,请分享。

感谢

+0

您可以从页面加载时起24小时内计时器倒数,也可以向预定的时间点向下计数;这听起来像你想要后者。如果是这样,你至少需要在你的代码的某个地方有时间戳 – Aron

+0

你好阿隆,我将如何创建时间戳,以便它从当前时间创建一个24小时的邮票 –

+0

请参阅我的答案。它回答你的问题吗? – Aron

回答

0

这是我会怎么做:

// 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 
... 
+1

从这我可以设置我想要的时间作为它的时间戳和倒计时。谢谢阿隆。 –

+0

非常好,如果我的答案有帮助,请将它标记为接受:) – Aron

+1

绝对会这样做 –

0

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

+0

哈利,如果我确实保存服务器上的时间戳,我将如何为用户分配唯一的计时器(假设他们单击按钮)。 –

+0

现在又回到了在客户端的localStorage(或cookie)中保存某种id。 –