無論是獲取短信碼,還是在活動頁輪詢獲取當前活動最新信息,都需要用到定時器。 但是,定時器如果不及時合理地清除,會造成業務邏輯混亂甚至應用卡死的情況。 uni-app 中在某個頁面中啟動定時器后,一定要在頁面關閉時將定時器清除掉。即在頁面卸載(關閉)的生命周期函數里,清除定時器。
<template> <view class="content"> <button class="btn" type="primary" @click="getCode">{{ text }}</button> </view> </template> <script> export default { data() { return { timer: null, text: '獲取驗證碼', status: false, num: 60 } }, methods: { getCode() { if (this.status) { return } this.status = true; this.loading(); this.timer = setInterval(() => { if (this.num === 0) { this.timer && this.clearTimer(); this.reset(); } else { this.loading(); } }, 1000); }, reset() { this.num = 60; this.loadingStatus = false; this.text = '獲取驗證碼'; }, loading() { this.num -= 1; this.text = '獲取中(' + this.num + ')'; }, clearTimer() { clearInterval(this.timer); this.timer = null; } }, onUnload: function() { this.timer && this.clearTimer(); } } </script> <style> .content { display: flex; justify-content: center; align-items: center; height: 750upx; } .btn { width: 400upx; } </style>
測試可能有個問題,到時間清除之后,再次點擊沒有在計時