在使用以前須要先在page頁引入wxTimer.js文件(這裏我將文件放在/utils)ios
let timer = require('../../utils/wxTimer.js');
而後就能夠使用啦git
調用以下:小程序
let wxTimer = new timer({ expired_at: "2018-9-27 23:28:00.14756", complete: function () { console.log("完成了") }, expired: function () { console.log("過時了(結束時間小於當前時間)") }, }) wxTimer.start(this); wxTimer.stop();
封裝方法中由於用到page頁的data,所以須要在調用start()的時候傳入 this函數
在data中添加timer對象ui
data:{ timer: { remaining: '00:00:00' } }
在頁面中就能夠經過 timer.remaining 就能夠顯示倒計時this
在調用wxTimer的時候,expired_at傳入的值須要特別留意。spa
在小程序開發中,ios是個很頭疼的事情,下面就「時間」來簡單的說一下prototype
對於上面代碼中提到的 2018-9-27 23:28:00.14756 code
在ios中是不支持‘-’的,應該替換爲 '/'對象
還有就是在ios中不支持 ‘.’ ,因此應該將'.'以後的數字去掉
在方法中這些都已經實現了,若是想了解詳細能夠查看代碼
參數說明:
expired_at:倒計時結束時間
complete:回調函數,倒計時結束後調用改方法
expired:回調函數,當傳入的時間過時時調用該方法
馬雲地址:https://gitee.com/WoRuoYiRuFeng/wx_smallProgram_countDown
附件(wxTimer.js)
1 var wxTimer = function (initObj) { 2 initObj = initObj || {}; 3 this.complete = initObj.complete; //結束任務(方法) 4 this.expired = initObj.expired; //過時執行(方法) 5 6 this.intervarID; //計時ID 7 this.expired_at = initObj.expired_at || "00:00:00"; //過時時間 8 } 9 10 wxTimer.prototype = { 11 //開始 12 start: function (self) { 13 let that = this; 14 let expired_at = new Date(that.expired_at.replace(/-/g, "/")).getTime(); 15 // expired_at = new Date(expired_at).getTime(); // ios下不執行,返回爲null 16 let nowTime = new Date().getTime(); 17 let remaining = (expired_at - nowTime); //計算剩餘的毫秒數 18 // 過時 19 if (remaining < 0) { 20 if (that.expired) { 21 that.expired(); 22 } 23 return 24 } 25 function begin() { 26 // 過時 27 // if (remaining < 0) { 28 // if (that.expired) { 29 // that.expired(); 30 // } 31 // that.stop(); 32 // }else{ 33 34 let hours = parseInt(remaining / 1000 / 60 / 60 % 24, 10); //計算剩餘的小時 35 let minutes = parseInt(remaining / 1000 / 60 % 60, 10);//計算剩餘的分鐘 36 let seconds = parseInt(remaining / 1000 % 60, 10);//計算剩餘的秒數 37 hours = checkTime(hours); 38 minutes = checkTime(minutes); 39 seconds = checkTime(seconds); 40 // 結束任務 41 if (hours <= 0 && minutes <= 0 && seconds <= 0) { 42 if (that.complete) { 43 that.complete(); 44 } 45 that.stop(); 46 } 47 if (hours >= 0 || minutes >= 0 || seconds >= 0) { 48 self.setData({ 49 ['timer.remaining']: hours + ":" + minutes + ":" + seconds 50 }); 51 } 52 remaining = remaining - 1000; 53 // } 54 } 55 function checkTime(timer){ 56 if (timer < 10){ 57 timer = "0" + timer; 58 } 59 return timer; 60 } 61 // begin(); 62 this.intervarID = setInterval(begin, 1000); 63 }, 64 //結束 65 stop: function () { 66 clearInterval(this.intervarID); 67 } 68 } 69 70 module.exports = wxTimer;