总是迟到了,但这里有一个我早些时候发表。似乎很遗憾浪费它。
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);