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

Jam*_*are 3 javascript timer momentjs

我需要帮助在 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>
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Aro*_*ron 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);
Run Code Online (Sandbox Code Playgroud)

这将每秒打印一个时间戳,如下所示:

09:49:25 
09:49:24 
09:49:23 
09:49:22 
...
Run Code Online (Sandbox Code Playgroud)

  • 由此我可以将我想要的时间设置为时间戳和倒计时。谢谢阿伦。 (2认同)