有没有办法可以为我的计时器添加毫秒数?
我目前正在使用这个计时器,但它只能在几秒钟内完成。
var count=99;
var counter=setInterval(timer, 1000); //1000 will run it every 1 second
function timer(){
count=count-1;
if (count <= 0){
clearInterval(counter);
return;
}
document.getElementById("timer").innerHTML=count + " seconds"; // watch for spelling
}
由于
答案 0 :(得分:5)
定时器不会以毫秒精度运行 - 不仅低于标准JS最小超时,定时器事件可以排队等各种其他问题。无论如何(没有双关语意)你实际上看不到计时器每秒计数1000次。
只需使用window.requestAnimationFrame
代替并显示传递给该函数的时间与计时器的参考开始时间之间的差异。
var timer = document.getElementById('timer');
var expires = +new Date() + 10000;
(function update() {
var now = +new Date();
var togo = expires - now;
if (togo > 0) {
timer.innerHTML = togo;
window.requestAnimationFrame(update);
} else {
timer.innerHTML = 0;
}
})();
<div id="timer"></div>
答案 1 :(得分:0)
参加派对总是迟到,但这是我之前提出的。浪费它似乎是一种耻辱。
function countdownTimer(el,duration){
var exp = Date.now() + duration;//expires in now + duration milliseconds
//callback using window.requestAnimationFrame if available else setTimeout at 60fps:
var rAF = window.requestAnimationFrame || function(callback){window.setTimeout(callback,1000/60);};
//left-pad with leading zeros
function pad(n,s){
s = s||2;
return ("00000"+n).substr(-s);
}
//The loopy bit:
//note the use of a bitwise right-shift to convert to int (http://jsperf.com/number-vs-parseint-vs-plus/39)
(function update() {
var n = Date.now(),
e = (exp-n),
ms= (e%1000),
s = ((e/1000)%60) >> 0,
m = ((e/(1000*60))%60) >> 0,
h = ((e/(1000*60*60))%24) >> 0;
if (e > 0) {
el.innerHTML = pad(h)+":"+pad(m)+":"+pad(s)+":"+pad(ms,3);
rAF(update);
} else {
el.innerHTML = "00:00:00:000";
}
})();//IIFE (Immediately-Invoked Function Expression)
};
countdownTimer(document.getElementById('timer'),10000);