[英]javascript countdown stutter
我有一个像这样的倒计时:
var countdown = {
startInterval: function() {
var count = 600
var countorig = 600;
var currentId = setInterval(function() {
var min = (count - (count % 60)) / 60;
var sec = count % 60;
if (sec < 10) {
$('#timer').html(min + ':0' + sec);
} else {
$('#timer').html(min + ':' + sec);
}
$('#time').val(countorig - count);
if (count == 0) {
$('#form').submit();
}--count;
}, 1000);
countdown.intervalId = currentId;
}
};
有用。 但是,如果我加载页面,倒计时开始,但它口吃它不像时钟那样“圆”。
JSFiddle 。
setInterval
不准确。 您应该使用Date
s来获得准确的时间,然后选择小于一秒的间隔以获得更平滑的时钟。 这是一个演示!
var countdown = {
startInterval: function() {
var count = 600;
var start = new Date(); // The current date!
var currentId = setInterval(function() {
var difference = Math.max(0, count - (new Date() - start) / 1000 | 0);
var min = difference / 60 | 0;
var sec = difference % 60;
$('#timer').text(min + ':' + (sec < 10 ? '0' : '') + sec);
$('#time').val(difference);
if(count === 0) {
$('#form').submit();
}
}, 200);
countdown.intervalId = currentId;
}
};
假设你的计时器是准确的,这绝不是一个好主意。 相反,使用增量计时。
var startTime = new Date().getTime();
setInterval(function() {
var elapsed = new Date().getTime()-startTime;
console.log("Been running for "+Math.floor(elapsed/1000)+" seconds");
},25);
这是因为setInterval并不是高分辨率计时器。 它不会在点上每1000毫秒命中一次。 您可能在任一方向上摆动20到30毫秒,导致时钟关闭。
使用Date.now()
,这是一个倒计时函数的快速示例( x
是毫秒)
function countdown(x){
var o = {future: Date.now()+x, last:-1, i:null}; // object so we can pass by-ref if req.
o.i = setInterval( function() { // use o.i so we can clear interval
var remain = o.future - Date.now(),
secs = Math.floor( remain / 1000 ),
mins = 0;
if( remain < 0 ){ // finished, do whatever
return clearInterval(o.i); // then clear & exit
}
if( secs === o.last ) return; // skip this iteration if it's not been a second
o.last = secs; // else update last time
// do whatever you want for this new second
if( secs > 59 ) mins = Math.floor( secs / 60 ), secs = secs % 60;
console.log(
(mins < 10 ? '0'+mins : mins) + ':' +
(secs < 10 ? '0'+secs : secs) + ' remain.'
);
}, 100);
}
如果你知道它不会在IE中使用,可以考虑在区间中将o
作为参数添加到回调函数中,也作为setInterval
的最后一个参数(因此它作为第一个arg传递给回调),这意味着闭包是独立的= >回调可以在任何地方定义。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.