因爲項目中不免會碰到須要實時刷新,不管是獲取短信碼,仍是在支付完成後輪詢獲取當前最新支付狀態,這時就須要用到定時器。 可是,定時器若是不及時合理地清除,會形成業務邏輯混亂甚至應用卡死的狀況,這個時就須要清除定時器。 某個頁面中啓動定時器後,必定要在頁面關閉時將定時器清除掉。即在頁面卸載(關閉)的生命週期函數裏,清除定時器。程序員
<template>
<view>
<button @click="getStatus">{{ buttonText }}</button>
</view>
</template>
<script>
export default {
data() {
return {
timer: null, //首先我在data函數裏面進行定義定時器名稱:
buttonText : '輪詢獲取訂單支付狀態',
timerNum: 60 // 設置定時器時間
}
},
methods: {
getStatus() {
this.loading(); // 啓動定時器
this.timer = setInterval(() => { //建立定時器
if (this.timerNum === 0) { // 設置的定時器時間爲0後執行的操做
this.timer && this.clearTimer(); // 關閉定時器
window.open('https://nav.imaring.com/', '_blank'); // 在新窗口打開程序員網址導航
} else {
this.loading();
}
}, 1000);
},
loading() { // 啓動定時器
this.timerNum -= 1; // 定時器減1
this.text = '獲取中(' + this.timerNum + ')';
},
clearTimer() {//清除定時器
clearInterval(this.timer);
this.timer = null;
}
},
// 最後在beforeDestroy()生命週期內清除定時器:
beforeDestroy() {
clearInterval(this.timer);
this.timer = null;
}
}
</script>
複製代碼
做爲一名碼農,隨着平時工做的須要,這裏收集了國內外不少優秀網站,這其中包括在線工具、在線運行、免費接口、在線資源、在線學習、技術論壇、技術博客等等,知足通常程序員平常需求。bash