倒計時的兩種用法:
一、計時器的用法
頁面部分
<span class="time-minute">{{timeMinute}}</span> <span class="time-unit">分</span> <span class="time-second">{{timeSecond}}</span> <span class="time-unit">秒</span>
js部分
export default { data() { return { // 倒計時 value:14, // 秒數 second:59, // 分鍾(定時器名稱) minute:null, // 毫秒(定時器名稱) millisecond:null, } } // 計算屬性 computed: { // 格式化倒計時分鍾 timeMinute() { if (this.value < 10) return `0${this.value}`; return this.value; }, timeSecond() { if (this.second < 10) return `0${this.second}`; return this.second; }, } // 關閉頁面 beforeDestroy() { // 清空分鍾定時器 clearInterval(this.minute); // 清空秒定時器 clearInterval(this.millisecond); // 分鍾(定時器名稱) this.minute=null, // 秒(定時器名稱) this.millisecond=null, }, // 方法 methods: { bearing() { this.sleepTen() // 倒計時分鍾 this.minute = setInterval(() => { if(this.value<0) this.value = 14 this.value -= 1 }, 60000); // 倒計時秒 this.millisecond = setInterval(() => { if(this.second<1) this.second = 60 this.second -=1 if(this.value<0 && this.second<1) { // 從新調取二維碼 this.renovate() } }, 1000); } } }
二、休眠用法
頁面還是上面的頁面
js部分
// 每一次跑的事件 sleep(duration) { return new Promise(resolve => { setTimeout(resolve, duration * 1000) }) }, // 執行倒計時 async sleepTen() { // 15分鍾總共的秒數 let timepredict = 15*60 // 循環去倒計時 for(; timepredict> 0; ) { // 每一次都減1並執行上面的事件 timepredict = timepredict - 1; await this.sleep(1); // 分鍾(取整) this.value = Math.floor(timepredict / 60); // 秒(取余) this.second = timepredict % 60; } },
優缺點對比:
1、休眠用法代碼要比計時器的代碼要少很多(代碼簡潔)
2、休眠用法他只要關閉這個頁面后,程序跑完只要你不做從新調取,它只會執行一遍,計時器如果你不關掉的話,會一直執行(需要設置開關)
3、倒計時上區分,時分秒只需要在for循環上進行計算就行了,不用在每一個方法去進行計算時分秒(計算簡潔)