做的一个小的倒计时,水平比较低,部分代码还待优化,欢迎阅读者指正:
$(function(){
function countDown(){
normalelapse = 10;
nextelapse = normalelapse;
counter = 0;
startTime = '';
timer = null;
time = new Array();
time[0] = time[1] = time[2] = '00';
}
countDown.prototype.run = function(tm){ //运行接口
var timerFunc = this.onTimer;
if(tm<10){
tm = '0' +tm;
}
time[0] = ''+tm;
counter = 0;
startTime = new Date().valueOf();
timer = setInterval(timerFunc,nextelapse);
}
countDown.prototype.insertDom = function(){ //dom 渲染
var mli = $('.time-m li');
var sli = $('.time-s li');
var msli = $('.time-ms li');
mli.empty();
sli.empty();
msli.empty();
armli = time[0].split('');
arsli = time[1].split('');
armsli = time[2].split('');
mli.eq('0').append(armli[0]);
mli.eq('1').append(armli[1]);
sli.eq('0').append(arsli[0]);
sli.eq('1').append(arsli[1]);
msli.eq('0').append(armsli[0]);
msli.eq('1').append(armsli[1]);
}
countDown.prototype.onTimer = function(){ //执行函数
console.log(time);
if(time[0]==0&&time[1]==0&&time[2]==0){
return;
}
time[2] -= 1;
time[2] += '';
if(time[2]<10&&time[2]>=0){
time[2] = '0' + time[2];
}
if(time[2]<0){
time[2] = '99';
time[1]-= 1;
time[1]+= '';
if(time[1]<10&&time[1]>=0){
time[1] = '0' +time[1];
}
if(time[1]<0){
time[1] = '59';
time[0] -= 1;
time[0] += '';
if(time[0]<10&&time[0]>=0){
time[0] = '0'+time[0];
}
}
}
//渲染数据到dom节点
countDown.prototype.insertDom(time);
clearInterval(timer);
//矫正下次触发的时间
counter++;
var counterSecs = counter * 10;
var elapseSecs = new Date().valueOf() - startTime;
var diffSecs = counterSecs - elapseSecs;
nextelapse = normalelapse + diffSecs;
if (nextelapse < 0) nextelapse = 0;
var timerFunc = countDown.prototype.onTimer;
timer = setInterval(timerFunc, nextelapse);
}
var timeDown = new countDown();
timeDown.run(1);
});
html如下
<ul>
<li>
<ul class="time-m">
<li class="i-time time-num">0</li>
<li class="i-time time-num">0</li>
</ul>
</li>
<li class="time-d">:</li>
<li>
<ul class="time-s">
<li class="i-time time-num">0</li>
<li class="i-time time-num">0</li>
</ul>
</li>
<li class="time-d">:</li>
<li>
<ul class="time-ms">
<li class="i-time time-num">0</li>
<li class="i-time time-num">0</li>
</ul>
</li>
</ul>