在使用之前需要先在page頁引入wxTimer.js文件(這里我將文件放在/utils)
let timer = require('../../utils/wxTimer.js');
然后就可以使用啦
調用如下:
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對象
data:{ timer: { remaining: '00:00:00' } }
在頁面中就可以通過 timer.remaining 就可以顯示倒計時
在調用wxTimer的時候,expired_at傳入的值需要特別留意。
在小程序開發中,ios是個很頭疼的事情,下面就“時間”來簡單的說一下
-
對於上面代碼中提到的 2018-9-27 23:28:00.14756
-
在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;
