背景
凹凸曼是個小程序開發者,他要在小程序實現秒殺倒計時。于是他不假思索,寫了以下代碼:
Page({init: function () {clearInterval(this.timer)this.timer = setInterval(() => {// 倒計時計算邏輯console.log('setInterval')})},
})
可是,凹凸曼發現頁面隱藏在后臺時,定時器還在不斷運行。于是凹凸曼優化了一下,在頁面展示的時候運行,隱藏的時候就暫停。
Page({onShow: function () {if (this.timer) {this.timer = setInterval(() => {// 倒計時計算邏輯console.log('setInterval')})}},onHide: function () {clearInterval(this.timer)},init: function () {clearInterval(this.timer)this.timer = setInterval(() => {// 倒計時計算邏輯console.log('setInterval')})},
})
問題看起來已經解決了,就在凹凸曼開心地搓搓小手暗暗歡喜時,突然發現小程序頁面銷毀時是不一定會調用 onHide 函數的,這樣定時器不就沒法清理了?那可是會造成內存泄漏的。凹凸曼想了想,其實問題不難解決,在頁面 onUnload 的時候也清理一遍定時器就可以了。
Page({...onUnload: function () {clearInterval(this.timer)},
})
這下問題都解決了,但我們可以發現,在小程序使用定時器需要很謹慎,一不小心就會造成內存泄漏。 后臺的定時器積累得越多,小程序就越卡,耗電量也越大,最終導致程序卡死甚至崩潰。特別是團隊開發的項目,很難確保每個成員都正確清理了定時器。因此,寫一個定時器管理庫來管理定時器的生命周期,將大有裨益。
思路整理
首先,我們先設計定時器的 API 規范,肯定是越接近原生 API 越好,這樣開發者可以無痛替換。
function $setTimeout(fn, timeout, ...arg) {}
function $setInterval(fn, timeout, ...arg) {}
function $clearTimeout(id) {}
function $clearInterval(id) {}
接下來我們主要解決以下兩個問題
如何實現定時器暫停和恢復
如何讓開發者無須在生命周期函數處理定時器
如何實現定時器暫停和恢復
思路如下:
將定時器函數參數保存,恢復定時器時重新創建
由于重新創建定時器,定時器 ID 會不同,因此需要自定義全局唯一 ID 來標識定時器
隱藏時記錄定時器剩余倒計時時間,恢復時使用剩余時間重新創建定時器
首先我們需要定義一個 Timer 類,Timer 對象會存儲定時器函數參數,代碼如下
class Timer {static count = 0/*** 構造函數* @param {Boolean} isInterval 是否是 setInterval* @param {Function} fn 回調函數* @param {Number} timeout 定時器執行時間間隔* @param {...any} arg 定時器其他參數*/constructor (isInterval = false, fn = () => {}, timeout = 0, ...arg) {this.id = ++Timer.count // 定時器遞增 idthis.fn = fnthis.timeout = timeoutthis.restTime = timeout // 定時器剩余計時時間this.isInterval = isIntervalthis.arg = arg}}// 創建定時器function $setTimeout(fn, timeout, ...arg) {const timer = new Timer(false, fn, timeout, arg)return timer.id}
接下來,我們來實現定時器的暫停和恢復,實現思路如下:
啟動定時器,調用原生 API 創建定時器并記錄下開始計時時間戳。
暫停定時器,清除定時器并計算該周期計時剩余時間。
恢復定時器,重新記錄開始計時時間戳,并使用剩余時間創建定時器。
代碼如下:
class Timer {constructor (isInterval = false, fn = () => {}, timeout = 0, ...arg) {this.id = ++Timer.count // 定時器遞增 idthis.fn = fnthis.timeout = timeoutthis.restTime = timeout // 定時器剩余計時時間this.isInterval = isIntervalthis.arg = arg}/*** 啟動或恢復定時器*/start() {this.startTime = +new Date()if (this.isInterval) {/* setInterval */const cb = (...arg) => {this.fn(...arg)/* timerId 為空表示被 clearInterval */if (this.timerId) this.timerId = setTimeout(cb, this.timeout, ...this.arg)}this.timerId = setTimeout(cb, this.restTime, ...this.arg)return}/* setTimeout */const cb = (...arg) => {this.fn(...arg)}this.timerId = setTimeout(cb, this.restTime, ...this.arg)}/* 暫停定時器 */suspend () {if (this.timeout > 0) {const now = +new Date()const nextRestTime = this.restTime - (now - this.startTime)const intervalRestTime = nextRestTime >=0 ? nextRestTime : this.timeout - (Math.abs(nextRestTime) % this.timeout)this.restTime = this.isInterval ? intervalRestTime : nextRestTime}clearTimeout(this.timerId)}
}
其中,有幾個關鍵點需要提示一下:
恢復定時器時,實際上我們是重新創建了一個定時器,如果直接用 setTimeout 返回的 ID 返回給開發者,開發者要 clearTimeout,這時候是清除不了的。因此需要在創建 Timer 對象時內部定義一個全局唯一 ID
this.id = ++Timer.count
,將該 ID 返回給 開發者。開發者 clearTimeout 時,我們再根據該 ID 去查找真實的定時器 ID (this.timerId)。計時剩余時間,timeout = 0 時不必計算;timeout > 0 時,需要區分是 setInterval 還是 setTimeout,setInterval 因為有周期循環,因此需要對時間間隔進行取余。
setInterval 通過在回調函數末尾調用 setTimeout 實現,清除定時器時,要在定時器增加一個標示位(this.timeId = "")表示被清除,防止死循環。
我們通過實現 Timer 類完成了定時器的暫停和恢復功能,接下來我們需要將定時器的暫停和恢復功能跟組件或頁面的生命周期結合起來,最好是抽離成公共可復用的代碼,讓開發者無須在生命周期函數處理定時器。翻閱小程序官方文檔,發現 Behavior 是個不錯的選擇。
Behavior
behaviors 是用于組件間代碼共享的特性,類似于一些編程語言中的 "mixins" 或 "traits"。 每個 behavior 可以包含一組屬性、數據、生命周期函數和方法,組件引用它時,它的屬性、數據和方法會被合并到組件中,生命周期函數也會在對應時機被調用。每個組件可以引用多個 behavior,behavior 也可以引用其他 behavior 。
// behavior.js 定義behavior
const TimerBehavior = Behavior({pageLifetimes: {show () { console.log('show') },hide () { console.log('hide') }},created: function () { console.log('created')},detached: function() { console.log('detached') }
})export { TimerBehavior }// component.js 使用 behavior
import { TimerBehavior } from '../behavior.js'Component({behaviors: [TimerBehavior],created: function () {console.log('[my-component] created')},attached: function () {console.log('[my-component] attached')}
})
如上面的例子,組件使用 TimerBehavior 后,組件初始化過程中,會依次調用 TimerBehavior.created() => Component.created() => TimerBehavior.show()
。 因此,我們只需要在 TimerBehavior 生命周期內調用 Timer 對應的方法,并開放定時器的創建銷毀 API 給開發者即可。 思路如下:
組件或頁面創建時,新建 Map 對象來存儲該組件或頁面的定時器。
創建定時器時,將 Timer 對象保存在 Map 中。
定時器運行結束或清除定時器時,將 Timer 對象從 Map 移除,避免內存泄漏。
頁面隱藏時將 Map 中的定時器暫停,頁面重新展示時恢復 Map 中的定時器。
const TimerBehavior = Behavior({created: function () {this.$store = new Map()this.$isActive = true},detached: function() {this.$store.forEach(timer => timer.suspend())this.$isActive = false},pageLifetimes: {show () {if (this.$isActive) returnthis.$isActive = truethis.$store.forEach(timer => timer.start(this.$store))},hide () {this.$store.forEach(timer => timer.suspend())this.$isActive = false}},methods: {$setTimeout (fn = () => {}, timeout = 0, ...arg) {const timer = new Timer(false, fn, timeout, ...arg)this.$store.set(timer.id, timer)this.$isActive && timer.start(this.$store)return timer.id},$setInterval (fn = () => {}, timeout = 0, ...arg) {const timer = new Timer(true, fn, timeout, ...arg)this.$store.set(timer.id, timer)this.$isActive && timer.start(this.$store)return timer.id},$clearInterval (id) {const timer = this.$store.get(id)if (!timer) returnclearTimeout(timer.timerId)timer.timerId = ''this.$store.delete(id)},$clearTimeout (id) {const timer = this.$store.get(id)if (!timer) returnclearTimeout(timer.timerId)timer.timerId = ''this.$store.delete(id)},}
})
上面的代碼有許多冗余的地方,我們可以再優化一下,單獨定義一個 TimerStore 類來管理組件或頁面定時器的添加、刪除、恢復、暫停功能。
class TimerStore {constructor() {this.store = new Map()this.isActive = true}addTimer(timer) {this.store.set(timer.id, timer)this.isActive && timer.start(this.store)return timer.id}show() {/* 沒有隱藏,不需要恢復定時器 */if (this.isActive) returnthis.isActive = truethis.store.forEach(timer => timer.start(this.store))}hide() {this.store.forEach(timer => timer.suspend())this.isActive = false}clear(id) {const timer = this.store.get(id)if (!timer) returnclearTimeout(timer.timerId)timer.timerId = ''this.store.delete(id)}
}
然后再簡化一遍 TimerBehavior
const TimerBehavior = Behavior({created: function () { this.$timerStore = new TimerStore() },detached: function() { this.$timerStore.hide() },pageLifetimes: {show () { this.$timerStore.show() },hide () { this.$timerStore.hide() }},methods: {$setTimeout (fn = () => {}, timeout = 0, ...arg) {const timer = new Timer(false, fn, timeout, ...arg)return this.$timerStore.addTimer(timer)},$setInterval (fn = () => {}, timeout = 0, ...arg) {const timer = new Timer(true, fn, timeout, ...arg)return this.$timerStore.addTimer(timer)},$clearInterval (id) {this.$timerStore.clear(id)},$clearTimeout (id) {this.$timerStore.clear(id)},}
})
此外,setTimeout 創建的定時器運行結束后,為了避免內存泄漏,我們需要將定時器從 Map 中移除。稍微修改下 Timer 的 start 函數,如下:
class Timer {// 省略若干代碼start(timerStore) {this.startTime = +new Date()if (this.isInterval) {/* setInterval */const cb = (...arg) => {this.fn(...arg)/* timerId 為空表示被 clearInterval */if (this.timerId) this.timerId = setTimeout(cb, this.timeout, ...this.arg)}this.timerId = setTimeout(cb, this.restTime, ...this.arg)return}/* setTimeout */const cb = (...arg) => {this.fn(...arg)/* 運行結束,移除定時器,避免內存泄漏 */timerStore.delete(this.id)}this.timerId = setTimeout(cb, this.restTime, ...this.arg)}
}
愉快地使用
從此,把清除定時器的工作交給 TimerBehavior 管理,再也不用擔心小程序越來越卡。
import { TimerBehavior } from '../behavior.js'// 在頁面中使用
Page({behaviors: [TimerBehavior],onReady() {this.$setTimeout(() => {console.log('setTimeout')})this.$setInterval(() => {console.log('setTimeout')})}
})// 在組件中使用
Components({behaviors: [TimerBehavior],ready() {this.$setTimeout(() => {console.log('setTimeout')})this.$setInterval(() => {console.log('setTimeout')})}
})
npm 包支持
為了讓開發者更好地使用小程序定時器管理庫,我們整理了代碼并發布了 npm 包供開發者使用,開發者可以通過 npm install --save timer-miniprogram
安裝小程序定時器管理庫,文檔及完整代碼詳看 https://github.com/o2team/timer-miniprogram
eslint 配置
為了讓團隊更好地遵守定時器使用規范,我們還可以配置 eslint 增加代碼提示,配置如下:
// .eslintrc.js
module.exports = {'rules': {'no-restricted-globals': ['error', {'name': 'setTimeout','message': 'Please use TimerBehavior and this.$setTimeout instead. see the link: https://github.com/o2team/timer-miniprogram'}, {'name': 'setInterval','message': 'Please use TimerBehavior and this.$setInterval instead. see the link: https://github.com/o2team/timer-miniprogram'}, {'name': 'clearInterval','message': 'Please use TimerBehavior and this.$clearInterval instead. see the link: https://github.com/o2team/timer-miniprogram'}, {'name': 'clearTimout','message': 'Please use TimerBehavior and this.$clearTimout instead. see the link: https://github.com/o2team/timer-miniprogram'}]}
}
總結
千里之堤,潰于蟻穴。
管理不當的定時器,將一點點榨干小程序的內存和性能,最終讓程序崩潰。
重視定時器管理,遠離定時器泄露。
參考資料
[1]
小程序開發者文檔: https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/behaviors.html
推薦閱讀
我在阿里招前端,我該怎么幫你?(文末有福利)
如何拿下阿里巴巴 P6 的前端 Offer
如何準備阿里P6/P7前端面試--項目經歷準備篇
大廠面試官常問的亮點,該如何做出?
如何從初級到專家(P4-P7)打破成長瓶頸和有效突破
若川知乎問答:2年前端經驗,做的項目沒什么技術含量,怎么辦?
末尾
你好,我是若川,江湖人稱菜如若川,歷時一年只寫了一個學習源碼整體架構系列~(點擊藍字了解我)
關注我的公眾號
若川視野
,回復"pdf" 領取前端優質書籍pdf我的博客地址:https://lxchuan12.gitee.io?歡迎收藏
覺得文章不錯,可以點個
在看
呀^_^另外歡迎留言
交流~
小提醒:若川視野公眾號面試、源碼等文章合集在菜單欄中間
【源碼精選】
按鈕,歡迎點擊閱讀