手把手教你寫個小程序定時器管理庫

背景

凹凸曼是個小程序開發者,他要在小程序實現秒殺倒計時。于是他不假思索,寫了以下代碼:

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) {}

接下來我們主要解決以下兩個問題

  1. 如何實現定時器暫停和恢復

  2. 如何讓開發者無須在生命周期函數處理定時器

如何實現定時器暫停和恢復

思路如下:

  1. 將定時器函數參數保存,恢復定時器時重新創建

  2. 由于重新創建定時器,定時器 ID 會不同,因此需要自定義全局唯一 ID 來標識定時器

  3. 隱藏時記錄定時器剩余倒計時時間,恢復時使用剩余時間重新創建定時器

首先我們需要定義一個 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}

接下來,我們來實現定時器的暫停和恢復,實現思路如下:

  1. 啟動定時器,調用原生 API 創建定時器并記錄下開始計時時間戳。

  2. 暫停定時器,清除定時器并計算該周期計時剩余時間。

  3. 恢復定時器,重新記錄開始計時時間戳,并使用剩余時間創建定時器。

代碼如下:

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)}
}

其中,有幾個關鍵點需要提示一下:

  1. 恢復定時器時,實際上我們是重新創建了一個定時器,如果直接用 setTimeout 返回的 ID 返回給開發者,開發者要 clearTimeout,這時候是清除不了的。因此需要在創建 Timer 對象時內部定義一個全局唯一 ID this.id = ++Timer.count,將該 ID 返回給 開發者。開發者 clearTimeout 時,我們再根據該 ID 去查找真實的定時器 ID (this.timerId)。

  2. 計時剩余時間,timeout = 0 時不必計算;timeout > 0 時,需要區分是 setInterval 還是 setTimeout,setInterval 因為有周期循環,因此需要對時間間隔進行取余。

  3. 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 給開發者即可。 思路如下:

  1. 組件或頁面創建時,新建 Map 對象來存儲該組件或頁面的定時器。

  2. 創建定時器時,將 Timer 對象保存在 Map 中。

  3. 定時器運行結束或清除定時器時,將 Timer 對象從 Map 移除,避免內存泄漏。

  4. 頁面隱藏時將 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年前端經驗,做的項目沒什么技術含量,怎么辦?

末尾

你好,我是若川,江湖人稱菜如若川,歷時一年只寫了一個學習源碼整體架構系列~(點擊藍字了解我)

  1. 關注我的公眾號若川視野,回復"pdf" 領取前端優質書籍pdf

  2. 我的博客地址:https://lxchuan12.gitee.io?歡迎收藏

  3. 覺得文章不錯,可以點個在看呀^_^另外歡迎留言交流~

小提醒:若川視野公眾號面試、源碼等文章合集在菜單欄中間【源碼精選】按鈕,歡迎點擊閱讀

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/276443.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/276443.shtml
英文地址,請注明出處:http://en.pswp.cn/news/276443.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

[New Portal]Windows Azure Virtual Machine (14) 在本地制作數據文件VHD并上傳至Azure(1)

《Windows Azure Platform 系列文章目錄》 之前的內容里,我介紹了如何將本地的Server 2012中文版 VHD上傳至Windows Azure,并創建基于該Server 2012 VHD的虛擬機。 我們知道,VHD不僅僅可以保存操作系統,而且可以保存數據文件。 如…

python 退出程序_Python:用Ctrl+C解決終止多線程程序的問題!(建議收藏)

前言:今天為大家帶來的內容是Python:用CtrlC解決終止多線程程序的問題!文章中的代碼具有不錯的參考意義,希望在此能夠幫助到各位!(多數代碼用圖片的方式呈現出來,方便各位觀看與收藏)出發點:前段時間&#…

Mysql InnoDB Plugin安裝 install

轉載鏈接:http://www.orczhou.com/index.php/2010/03/innodb-plugin-setup/ InnoDB Plugin較之Built-in版本新增了很多特性:包括快速DDL、壓縮存儲等,而且引入了全新的文件格式Barracuda。眾多測試也表明,Plugin在很多方面優于Bu…

Hibernate的數據過濾查詢

數據過濾并不是一種常規的數據查詢方法,而是一種整體的篩選方法。數據過濾也可對數據進行篩選,因此,將其放在Hibernate的數據查詢框架中介紹。 如果一旦啟用了數據過濾器,則不管數據查詢,還是數據加載,該過…

若川知乎高贊:有哪些必看的 JS 庫?

歡迎星標我的公眾號,回復加群,長期交流學習我的知乎回答目前2w閱讀量,270贊,現在發到公眾號聲明原創。必看的js庫?只有當前階段值不值看。我從去年7月起看一些前端庫的源碼,歷時一年才寫了八篇《學習源碼整…

python用for循環求10的因數_python for循環練習(初級)

for循環練習1for i in range(4):print(i)D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/test.py0123for循環練習2for x in range(1,40,5): #間隔5print(x)D:\尚硅谷Python\venv\Scripts\python.exe D:/尚硅谷Python/test.py16111621263136打印99乘法表for i in ran…

基于EasyUI的Web應用程序及過去一年的總結

前言 一個多月之前已經提交了離職申請,好在領導都已經批準了,過幾天就辦理手續了,在此感謝領導的栽培與挽留,感謝各位同事在工作中的給我的幫助,離開這個團隊確實有一些不舍,不為別的,只因為這個…

MySQL外鍵創建失敗1005原因總結

1、安裝mysql有InnoDB的插件擴展 ./configure --prefix/usr/local/mysql --with-pluginscsv,innobase,myisam,heap,innodb_plugin 2、找不到主表中 引用的列 3、主鍵和外鍵的字符編碼不一致 4、外鍵字段與要做外鍵校驗的字段類型不匹配 5、MySQL支持外鍵約束,并…

Hibernate的事件機制

4.8 事 件 機 制 通常,Hibernate執行持久化過程中,應用程序無法參與其中。所有的數據持久化操作,對用戶都是透明的,用戶無法插入自己的動作。 通過事件框架,Hibernate允許應用程序能響應特定的內部事件,從而…

快速使用Vue3最新的15個常用API

之前我寫了一篇博客介紹了Vue3的新特性,簡單了解了一下Vue3都有哪些特色,并且在文末帶大家稍微體驗了一下Vue3中 Compsition API 的簡單使用上一篇文章地址:緊跟尤大的腳步提前體驗Vue3新特性,你不會還沒了解過Vue3吧因為這個月的…

超級馬里奧代碼_任天堂的源碼泄露,揭示超級馬里奧的前世之生

被黑客盯上的任天堂任天堂遭到了史上最大規模的黑客攻擊,Wii 完整源碼、設計以及《寶可夢》多部作品的信息遭到泄露,而此次泄露事件的后續影響似乎也爆發了出來。《馬里奧賽車》和《超級馬里奧世界2》(耀西島)的早期原型視頻,以及《超級馬里奧…

行者寂寞

公元2009年7月20日。閏五月廿八。炎日,汗如雨。晨行。病臥于京西客站。是夜,不能寐。 公元2009年7月21日。閏五月廿九。戲于清華,游于星巴克。汗如雨。是夜,困于京國際機場5小時。 公元2009年7月22日。六月初一。晨時抵寧。大雨。…

Azure PowerShell (1) PowerShell整理

《Windows Azure Platform 系列文章目錄》 把之前Azure ASM的PowerShell都整理好了。 https://github.com/leizhang1984/AzureChinaPowerShell

漫畫 | 前端發展史的江湖恩怨情仇

時間總是過得很快, 似乎快得讓人忘記了昨天,前端WEB領域的發展更是如此,轉眼間已是近30年,時光荏苒,初心不變,在一代又一代前端人的努力下,前端已經是互聯網不可或缺的一部分。然而很多前端打工…

jquery1.9 下檢測瀏覽器類型和版本

原文鏈接:http://blog.csdn.net/lyc_2011_acm/article/details/8749177 Jquery1.9版本中$.browser已被剔除: 判斷瀏覽器類型: $.browser.mozilla /firefox/.test(navigator.userAgent.toLowerCase()); $.browser.webkit /webkit/.test(nav…

python可迭代對象 迭代器生成器_Python可迭代對象、迭代器和生成器

8.1 可迭代對象(Iterable)大部分對象都是可迭代,只要實現了__iter__方法的對象就是可迭代的。__iter__方法會返回迭代器(iterator)本身,例如:>>> lst [1,2,3]>>> lst.__iter__()Python提供一些語句和關鍵字用于訪問可迭代…

Windows Mobile下使用CppUnitLite輸出測試結果

背景 TDD測試驅動開發是當前流行的開發方法及模式。遵循TDD的方法對開發程序庫(Library)特別有用,因為Library就是為第三方提供一定功能接口的實現,使用TDD的方法可以預先為定義的接口提供測試案例,保證實現代碼能通過測試,保證Li…

sql注意事項2點

①對Null的判斷,如果要用<>與null判斷,則都會得到否定結果②insert into時,要把字段顯示指出,不然會因字段位置變化出錯③-一個數時,如果有可能存在Null,則結果會被置為Null解決方法,select出來的結果,最好加isnull判斷轉載于:https://www.cnblogs.com/lishenglyx/archiv…

PHP IE中下載附件問題

重點&#xff1a; 1、在IE中下載附件之前要清空緩存。 2、中文文件名要用urlencode編碼。 Header("Pragma: "); //不加的話&#xff0c;IE中會提示目標主機無法訪問 Header("Cache-Control: "); //不加的話&#xff0c;IE中會提示目標…

10 個你可能還不知道 VS Code 使用技巧

經常幫一些同學 One-on-One 地解決問題&#xff0c;在看部分同學使用 VS Code 的時候&#xff0c;有些蹩腳&#xff0c;實際上一些有用的技巧能夠提高我們的日常工作效率。NO.1一、重構代碼VS Code 提供了一些快速重構代碼的操作&#xff0c;例如&#xff1a;將一整段代碼提取為…