jQuery 使用 Moment js 的倒数计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16129157/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Countdown timer using Moment js
提问by Arpit Rawat
I am making a countdown timer for an event page, i used moment js for this.
我正在为事件页面制作倒数计时器,为此我使用了 moment js。
Here is fiddlefor this.
这是小提琴。
I am calculating date difference between event date and current date (timestamp), then using "duration" method from moment js. But the time left is not coming as expected.
Expected- 00:30m:00s
Actual- 5h:59m:00s
我正在计算事件日期和当前日期(时间戳)之间的日期差异,然后使用 moment js 中的“持续时间”方法。但剩下的时间并没有像预期的那样到来。
预期- 00:30m:00s
实际- 5h:59m:00s
Code :
代码 :
<script>
$(document).ready(function(){
var eventTime = '1366549200';
var currentTime = '1366547400';
var time = eventTime - currentTime;
var duration = moment.duration(time*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
});
</script>
I read the momentjs documentation to figure out the problem, but no luck.
我阅读了 momentjs 文档以找出问题所在,但没有运气。
Thanks for your time.
谢谢你的时间。
Update :
更新 :
I end up doing like this :
我最终这样做:
<script>
$(document).ready(function(){
var eventTime = '1366549200';
var currentTime = '1366547400';
var leftTime = eventTime - currentTime;//Now i am passing the left time from controller itself which handles timezone stuff (UTC), just to simply question i used harcoded values.
var duration = moment.duration(leftTime, 'seconds');
var interval = 1000;
setInterval(function(){
// Time Out check
if (duration.asSeconds() <= 0) {
clearInterval(intervalId);
window.location.reload(true); #skip the cache and reload the page from the server
}
//Otherwise
duration = moment.duration(duration.asSeconds() - 1, 'seconds');
$('.countdown').text(duration.days() + 'd:' + duration.hours()+ 'h:' + duration.minutes()+ 'm:' + duration.seconds() + 's');
}, interval);
});
</script>
回答by Diode
In the last statement you are converting the duration to time which also considers the timezone. I assume that your timezone is +530, so 5 hours and 30 minutes gets added to 30 minutes. You can do as given below.
在最后一条语句中,您将持续时间转换为也考虑时区的时间。我假设您的时区是 +530,所以 5 小时 30 分钟被添加到 30 分钟。您可以按照下面的说明进行操作。
var eventTime= 1366549200; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTime = 1366547400; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var diffTime = eventTime - currentTime;
var duration = moment.duration(diffTime*1000, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration - interval, 'milliseconds');
$('.countdown').text(duration.hours() + ":" + duration.minutes() + ":" + duration.seconds())
}, interval);
回答by Leniel Maccaferri
Check out this plugin:
看看这个插件:
moment-countdown is a tiny moment.jsplugin that integrates with Countdown.js. The file is here.
moment-countdown 是一个与Countdown.js集成的小moment.js插件 。文件在这里。
How it works?
这个怎么运作?
//from then until now
moment("1982-5-25").countdown().toString(); //=> '30 years, 10 months, 14 days, 1 hour, 8 minutes, and 14 seconds'
//accepts a moment, JS Date, or anything parsable by the Date constructor
moment("1955-8-21").countdown("1982-5-25").toString(); //=> '26 years, 9 months, and 4 days'
//also works with the args flipped, like diff()
moment("1982-5-25").countdown("1955-8-21").toString(); //=> '26 years, 9 months, and 4 days'
//accepts all of countdown's options
moment().countdown("1982-5-25", countdown.MONTHS|countdown.WEEKS, NaN, 2).toString(); //=> '370 months, and 2.01 weeks'
回答by Jeremy Iglehart
Although I'm sure this won't be accepted as the answer to this very old question, I came here looking for a way to do this and this is how I solved the problem.
虽然我确信这不会被接受作为这个非常古老问题的答案,但我来到这里是为了寻找一种方法来解决这个问题,这就是我解决问题的方法。
I created a demonstration here at codepen.io.
我在 codepen.io 上创建了一个演示。
The Html:
Html:
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
The time is now: <span class="now"></span>, a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>
The Javascript:
Javascript:
var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);
$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
$(".difference > span").text(moment().to(then));
$(".countdown").text(countdown(then).toString());
requestAnimationFrame(timerLoop);
})();
Output:
输出:
The time is now: 5:29:35 pm, a timer will go off in a minute at 5:30:35 pm
The timer is set to go off in a minute
1 minute
Note: 2nd line above updates as per momentjsand 3rd line above updates as per countdownjsand all of this is animated at about ~60FPS because of requestAnimationFrame()
注意:上面的第 2 行按照momentjs更新,上面的第 3 行按照countdownjs更新,所有这些都以大约 60FPS 的速度进行动画处理,因为requestAnimationFrame()
Code Snippet:
代码片段:
Alternatively you can just look at this code snippet:
或者,您可以查看此代码片段:
var now = moment(); // new Date().getTime();
var then = moment().add(60, 'seconds'); // new Date(now + 60 * 1000);
$(".now").text(moment(now).format('h:mm:ss a'));
$(".then").text(moment(then).format('h:mm:ss a'));
$(".duration").text(moment(now).to(then));
(function timerLoop() {
$(".difference > span").text(moment().to(then));
$(".countdown").text(countdown(then).toString());
requestAnimationFrame(timerLoop);
})();
// CountdownJS: http://countdownjs.org/
// Rawgit: http://rawgit.com/
// MomentJS: http://momentjs.com/
// jQuery: https://jquery.com/
// Light reading about the requestAnimationFrame pattern:
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
// https://css-tricks.com/using-requestanimationframe/
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js" type="text/javascript"></script>
<script src="https://cdn.rawgit.com/mckamey/countdownjs/master/countdown.min.js" type="text/javascript"></script>
<script src="https://code.jquery.com/jquery-3.0.0.min.js" type="text/javascript"></script>
<div>
The time is now: <span class="now"></span>,
</div>
<div>
a timer will go off <span class="duration"></span> at <span class="then"></span>
</div>
<div class="difference">The timer is set to go off <span></span></div>
<div class="countdown"></div>
Requirements:
要求:
- CountdownJS: http://countdownjs.org/(And Rawgitto be able to use countdownjs)
- MomentJS: http://momentjs.com/
requestAnimationFrame()
- use this for animation rather thansetInterval()
.
- CountdownJS:http: //countdownjs.org/(和Rawgit才能使用 countdownjs)
- MomentJS:http://momentjs.com/
requestAnimationFrame()
- 将此用于动画而不是setInterval()
.
Optional Requirements:
可选要求:
- jQuery: https://jquery.com/
- jQuery:https: //jquery.com/
Additionally here is some light reading about the requestAnimationFrame()
pattern:
此外,这里有一些关于该requestAnimationFrame()
模式的轻松阅读:
- http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
- https://css-tricks.com/using-requestanimationframe/
- http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
- https://css-tricks.com/using-requestanimationframe/
I found the requestAnimationFrame()
pattern to be much a more elegant solution than the setInterval()
pattern.
我发现requestAnimationFrame()
模式是比setInterval()
模式更优雅的解决方案。
回答by amackay11
I thought I'd throw this out there too (no plugins). It counts down for 10 seconds into the future.
我想我也会把它扔出去(没有插件)。它倒计时 10 秒到未来。
var countDownDate = moment().add(10, 'seconds');
var x = setInterval(function() {
diff = countDownDate.diff(moment());
if (diff <= 0) {
clearInterval(x);
// If the count down is finished, write some text
$('.countdown').text("EXPIRED");
} else
$('.countdown').text(moment.utc(diff).format("HH:mm:ss"));
}, 1000);
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="countdown"></div>
回答by Lemurr
Timezones. You have to deal with them, by using getTimezoneOffset()
if you want your visitors from around the wolrd to get the same time.
时区。getTimezoneOffset()
如果您希望来自世界各地的访问者获得相同的时间,则必须通过使用来处理它们。
Try this http://jsfiddle.net/cxyms/2/, it works for me, but I'm not sure will it work with other timezones.
试试这个http://jsfiddle.net/cxyms/2/,它对我有用,但我不确定它是否适用于其他时区。
var eventTimeStamp = '1366549200'; // Timestamp - Sun, 21 Apr 2013 13:00:00 GMT
var currentTimeStamp = '1366547400'; // Timestamp - Sun, 21 Apr 2013 12:30:00 GMT
var eventTime = new Date();
eventTime.setTime(366549200);
var Offset = new Date(eventTime.getTimezoneOffset()*60000)
var Diff = eventTimeStamp - currentTimeStamp + (Offset.getTime() / 2);
var duration = moment.duration(Diff, 'milliseconds');
var interval = 1000;
setInterval(function(){
duration = moment.duration(duration.asMilliseconds() - interval, 'milliseconds');
$('.countdown').text(moment(duration.asMilliseconds()).format('H[h]:mm[m]:ss[s]'));
}, interval);
回答by Stephen R
The following also requires the moment-duration-format plugin:
以下还需要moment-duration-format 插件:
$.fn.countdown = function ( options ) {
var $target = $(this);
var defaults = {
seconds: 0,
format: 'hh:mm:ss',
stopAtZero: true
};
var settings = $.extend(defaults, options);
var eventTime = Date.now() + ( settings.seconds * 1000 );
var diffTime = eventTime - Date.now();
var duration = moment.duration( diffTime, 'milliseconds' );
var interval = 0;
$target.text( duration.format( settings.format, { trim: false }) );
var counter = setInterval(function () {
$target.text( moment.duration( duration.asSeconds() - ++interval, 'seconds' ).format( settings.format, { trim: false }) );
if( settings.stopAtZero && interval >= settings.seconds ) clearInterval( counter );
}, 1000);
};
Usage example:
用法示例:
$('#someDiv').countdown({
seconds: 30*60,
format: 'mm:ss'
});
回答by Andrew Samole
Here's my timer for 5 minutes:
这是我的 5 分钟计时器:
var start = moment("5:00", "m:ss");
var seconds = start.minutes() * 60;
this.interval = setInterval(() => {
this.timerDisplay = start.subtract(1, "second").format("m:ss");
seconds--;
if (seconds === 0) clearInterval(this.interval);
}, 1000);