近來寫了不少微信端的互動小活動,比如下雪花、限時點擊領獎、限時拼圖、限時答題等,全都離不開「計時器」。說到計時器,用一個 setInterval 或 setTimeout 就能搞定,程式碼不超過十行。但既然要寫,不如抱著精益求精的心態,做一個能重複使用的計時器元件吧。
目標有兩個:一是能倒數計時也能順向計時;二是具備重置、暫停、停止、啟動等功能。
//計時器 window.timer = (function(){ function mod(opt){ //可配置參數 都帶有默認值 //必選參數 this.ele = typeof(opt.ele)=='string'?document.getElementById(opt.ele):opt.ele;//元素 //可選參數 this.startT = opt.startT||0;//時間基數 this.endT = opt.endT=='undefined'?24*60*60:opt.endT;//結束時間 默認為一天 this.setStr = opt.setStr||null;//字符串拼接 this.countdown = opt.countdown||false;//倒計時 this.step = opt.step||1000; //不可配置參數 this.timeV = this.startT;//當前時間 this.startB = false;//是否啟動了計時 this.pauseB = false;//是否暫停 this.init(); } mod.prototype = { constructor : 'timer', init : function(){ this.ele.innerHTML = this.setStr(this.timeV); }, start : function(){ if(this.pauseB==true||this.startB == true){ this.pauseB = false; return; } if(this.countdown==false&&this.endT<=this.cardinalNum){ return false; }else if(this.countdown==true&&this.endT>=this.startT){ return false; } this.startB = true; var v = this.startT, this_ = this, anim = null; anim = setInterval(function(){ if(this_.startB==false||v==this_.endT){clearInterval(anim);return false} if(this_.pauseB==true)return; this_.timeV = this_.countdown?--v:++v; this_.ele.innerHTML = this_.setStr(this_.timeV); },this_.step); }, reset : function(){ this.startB = false; this.timeV = this.startT; this.ele.innerHTML = this.setStr(this.timeV); }, pause : function(){ if(this.startB == true)this.pauseB = true; }, stop : function(){ this.startB = false; } } return mod; })(); 呼叫方式:
var timerO_1 = new timer({ ele : 'BOX1', startT : 0, endT : 15, setStr : function(num){ return num+'s'; } }); var timerO_2 = new timer({ ele : 'BOX2', startT : 30, endT : 0, countdown : true, step : 500, setStr : function(num){ return num+'s'; } }); 這裡傳入的 setStr 是計時器在把當前時間寫入元素前,對數字做的字串處理函式;countdown 決定是倒數(true)還是順數(false,預設);而你可以隨時透過 timerO.timeV 取得當前時間。把計時邏輯封裝成一個可配置的模組後,無論順數、倒數還是暫停重置,都能一行 new 就搞定,重複利用性遠勝每次手寫 setInterval。