日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

手把手教你写个小程序定时器管理库

發(fā)布時間:2023/12/9 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 手把手教你写个小程序定时器管理库 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

背景

凹凸曼是個小程序開發(fā)者,他要在小程序?qū)崿F(xiàn)秒殺倒計時。于是他不假思索,寫了以下代碼:

Page({init: function () {clearInterval(this.timer)this.timer = setInterval(() => {// 倒計時計算邏輯console.log('setInterval')})}, })

可是,凹凸曼發(fā)現(xiàn)頁面隱藏在后臺時,定時器還在不斷運行。于是凹凸曼優(yōu)化了一下,在頁面展示的時候運行,隱藏的時候就暫停。

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

問題看起來已經(jīng)解決了,就在凹凸曼開心地搓搓小手暗暗歡喜時,突然發(fā)現(xiàn)小程序頁面銷毀時是不一定會調(diào)用 onHide 函數(shù)的,這樣定時器不就沒法清理了?那可是會造成內(nèi)存泄漏的。凹凸曼想了想,其實問題不難解決,在頁面 onUnload 的時候也清理一遍定時器就可以了。

Page({...onUnload: function () {clearInterval(this.timer)}, })

這下問題都解決了,但我們可以發(fā)現(xiàn),在小程序使用定時器需要很謹慎,一不小心就會造成內(nèi)存泄漏。 后臺的定時器積累得越多,小程序就越卡,耗電量也越大,最終導致程序卡死甚至崩潰。特別是團隊開發(fā)的項目,很難確保每個成員都正確清理了定時器。因此,寫一個定時器管理庫來管理定時器的生命周期,將大有裨益。

思路整理

首先,我們先設(shè)計定時器的 API 規(guī)范,肯定是越接近原生 API 越好,這樣開發(fā)者可以無痛替換。

function $setTimeout(fn, timeout, ...arg) {} function $setInterval(fn, timeout, ...arg) {} function $clearTimeout(id) {} function $clearInterval(id) {}

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

  • 如何實現(xiàn)定時器暫停和恢復

  • 如何讓開發(fā)者無須在生命周期函數(shù)處理定時器

  • 如何實現(xiàn)定時器暫停和恢復

    思路如下:

  • 將定時器函數(shù)參數(shù)保存,恢復定時器時重新創(chuàng)建

  • 由于重新創(chuàng)建定時器,定時器 ID 會不同,因此需要自定義全局唯一 ID 來標識定時器

  • 隱藏時記錄定時器剩余倒計時時間,恢復時使用剩余時間重新創(chuàng)建定時器

  • 首先我們需要定義一個 Timer 類,Timer 對象會存儲定時器函數(shù)參數(shù),代碼如下

    class Timer {static count = 0/*** 構(gòu)造函數(shù)* @param {Boolean} isInterval 是否是 setInterval* @param {Function} fn 回調(diào)函數(shù)* @param {Number} timeout 定時器執(zhí)行時間間隔* @param {...any} arg 定時器其他參數(shù)*/constructor (isInterval = false, fn = () => {}, timeout = 0, ...arg) {this.id = ++Timer.count // 定時器遞增 idthis.fn = fnthis.timeout = timeoutthis.restTime = timeout // 定時器剩余計時時間this.isInterval = isIntervalthis.arg = arg}}// 創(chuàng)建定時器function $setTimeout(fn, timeout, ...arg) {const timer = new Timer(false, fn, timeout, arg)return timer.id}

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

  • 啟動定時器,調(diào)用原生 API 創(chuàng)建定時器并記錄下開始計時時間戳。

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

  • 恢復定時器,重新記錄開始計時時間戳,并使用剩余時間創(chuàng)建定時器。

  • 代碼如下:

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

    其中,有幾個關(guān)鍵點需要提示一下:

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

  • 計時剩余時間,timeout = 0 時不必計算;timeout > 0 時,需要區(qū)分是 setInterval 還是 setTimeout,setInterval 因為有周期循環(huán),因此需要對時間間隔進行取余。

  • setInterval 通過在回調(diào)函數(shù)末尾調(diào)用 setTimeout 實現(xiàn),清除定時器時,要在定時器增加一個標示位(this.timeId = "")表示被清除,防止死循環(huán)。

  • 我們通過實現(xiàn) Timer 類完成了定時器的暫停和恢復功能,接下來我們需要將定時器的暫停和恢復功能跟組件或頁面的生命周期結(jié)合起來,最好是抽離成公共可復用的代碼,讓開發(fā)者無須在生命周期函數(shù)處理定時器。翻閱小程序官方文檔,發(fā)現(xiàn) Behavior 是個不錯的選擇。

    Behavior

    behaviors 是用于組件間代碼共享的特性,類似于一些編程語言中的 "mixins" 或 "traits"。 每個 behavior 可以包含一組屬性、數(shù)據(jù)、生命周期函數(shù)和方法,組件引用它時,它的屬性、數(shù)據(jù)和方法會被合并到組件中,生命周期函數(shù)也會在對應時機被調(diào)用。每個組件可以引用多個 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 后,組件初始化過程中,會依次調(diào)用 TimerBehavior.created() => Component.created() => TimerBehavior.show()。 因此,我們只需要在 TimerBehavior 生命周期內(nèi)調(diào)用 Timer 對應的方法,并開放定時器的創(chuàng)建銷毀 API 給開發(fā)者即可。 思路如下:

  • 組件或頁面創(chuàng)建時,新建 Map 對象來存儲該組件或頁面的定時器。

  • 創(chuàng)建定時器時,將 Timer 對象保存在 Map 中。

  • 定時器運行結(jié)束或清除定時器時,將 Timer 對象從 Map 移除,避免內(nèi)存泄漏。

  • 頁面隱藏時將 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)},} })

    上面的代碼有許多冗余的地方,我們可以再優(yōu)化一下,單獨定義一個 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 創(chuàng)建的定時器運行結(jié)束后,為了避免內(nèi)存泄漏,我們需要將定時器從 Map 中移除。稍微修改下 Timer 的 start 函數(shù),如下:

    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)/* 運行結(jié)束,移除定時器,避免內(nèi)存泄漏 */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 包支持

    為了讓開發(fā)者更好地使用小程序定時器管理庫,我們整理了代碼并發(fā)布了 npm 包供開發(fā)者使用,開發(fā)者可以通過 npm install --save timer-miniprogram 安裝小程序定時器管理庫,文檔及完整代碼詳看 https://github.com/o2team/timer-miniprogram

    eslint 配置

    為了讓團隊更好地遵守定時器使用規(guī)范,我們還可以配置 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'}]} }

    總結(jié)

    千里之堤,潰于蟻穴。

    管理不當?shù)亩〞r器,將一點點榨干小程序的內(nèi)存和性能,最終讓程序崩潰。

    重視定時器管理,遠離定時器泄露。

    參考資料

    [1]

    小程序開發(fā)者文檔: https://developers.weixin.qq.com/miniprogram/dev/framework/custom-component/behaviors.html

    推薦閱讀

    我在阿里招前端,我該怎么幫你?(文末有福利)
    如何拿下阿里巴巴 P6 的前端 Offer
    如何準備阿里P6/P7前端面試--項目經(jīng)歷準備篇
    大廠面試官常問的亮點,該如何做出?
    如何從初級到專家(P4-P7)打破成長瓶頸和有效突破
    若川知乎問答:2年前端經(jīng)驗,做的項目沒什么技術(shù)含量,怎么辦?

    末尾

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

  • 關(guān)注我的公眾號若川視野,回復"pdf" 領(lǐng)取前端優(yōu)質(zhì)書籍pdf

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

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

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

    總結(jié)

    以上是生活随笔為你收集整理的手把手教你写个小程序定时器管理库的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。

    主站蜘蛛池模板: 国产在线综合网 | 亚洲欧美变态另类丝袜第一区 | 波多野结衣一本 | 久久久999视频 | 久久午夜夜伦鲁鲁片无码免费 | 一区三区视频 | 91在线在线| 日韩影院一区二区 | 久久久av免费 | 337p日本欧洲亚洲大胆张筱雨 | 日韩av电影网站 | 黄色动漫软件 | 欧美激情久久久久久久 | 日韩久久高清 | 午夜国产福利视频 | 亚洲一区二区三区四 | 人人妻人人澡人人爽 | 久久看毛片| 色综合久久久久无码专区 | 人妻在线一区二区三区 | 亚洲第一福利视频 | 亚洲v欧美v另类v综合v日韩v | 成人tv | 亚洲精品成人区在线观看 | 日本激情网 | 国产成年网站 | 97香蕉超级碰碰久久免费软件 | 大桥未久恸哭の女教师 | 美女插插视频 | 福利视频免费看 | 亚洲黄色在线观看视频 | 96亚洲精品久久久蜜桃 | 51精品国产人成在线观看 | 精品伦精品一区二区三区视频密桃 | 天天看片天天干 | 欧美黄色成人 | 欧美午夜在线视频 | 欧美日韩精选 | 午夜免费视频观看 | 伊人日日夜夜 | 777中文字幕 | 老司机久久精品视频 | 欧美色图俺去了 | 秋霞影院午夜丰满少妇在线视频 | 国产美女一级视频 | 国产一区视频在线 | 亚洲成人福利在线 | 懂色tv | 午夜成年人视频 | 亚洲 欧美 成人 | 性色视频 | 加勒比日韩| 国产成人综合在线 | 国产精品秘入口18禁麻豆免会员 | 国产美女免费观看 | 欧美xxx在线观看 | 欧美日韩成人 | 日韩激情精品 | 17c一起操 | 麻豆毛片 | 天天综合网久久综合网 | av网站在线免费 | 日本jizzjizz| 肥熟女一区二区三肥熟女 | 91av综合 | 成人美女毛片 | 亚洲免费a | 日本亚洲黄色 | 黄色国产在线观看 | 天天夜夜啦啦啦 | 亚洲精品无码久久久 | 欧美不卡一区二区 | 国产一区二区四区 | 蜜桃色999 | 国产精品久久久久久久一区二区 | 久久久久久久久艹 | 天堂网久久 | 欧美搞逼视频 | 亚洲三级图片 | 午夜国产一区二区 | 性欧美丰满熟妇xxxx性仙踪林 | 久久国产黄色片 | 日韩第八页 | 中文字幕精品亚洲 | 免费看欧美大片 | 亚洲第一看片 | 男女高h视频| 伊在线久久丫 | 鲁鲁狠狠狠7777一区二区 | 丁香五香天堂网 | 在线视频观看 | 国产二三区 | 色七七在线 | 9色视频 | www久久久久| 丁香花电影在线观看免费高清 | 99r精品视频 | 日本人做受免费视频 | 成人免费视频免费观看 |