前言:我的項目中有一個需求需要用到函數防抖,但是發現小程序中防抖函數總是不生效,經過一番思考想到了下面的方法。
一,對於用JS開發的小程序
1. 首先直接定義防抖函數
2. 然后關鍵的一步, 在生命周期鈎子里初始化防抖函數
Page({ data: { num: 0 }, onLoad: function() { this.throttle = this.throttle(1000) // 初始化防抖函數 }, /** * 防抖函數 */ debounce(time) { let timeOut = null; return () => { if(timeOut) { console.log('觸發防抖,不執行回調'); clearTimeout(timeOut); } timeOut = setTimeout(() => { this.addNum() }, time); } }, /** * 被防抖函數 **/ addNum() { this.setData({ num: this.data.num + 1 }) console.log(`延遲 1 秒執行回調 ${this.data.num}`); }, })
效果:

二,對於用TS開發的小程序
ts寫的小程序實現函數防抖和js小程序略有不同,ts必須用 class 的方式實現, 下面我就用自己項目中的案例來展示
1. 創建防抖函數類
2. 在頁面生命周期里初始化類
3. 在目標函數里調用類的靜態方法--防抖函數
export class Debounce { static timeOut: any = null static callback: any = null public static init(callback, time) { this.callback = callback this.timeOut = time } public static search(detail) { // 這里的 detail 是為了接收頁面傳過來的數據 this.timeOut as any clearTimeout(this.timeOut); this.timeOut = setTimeout(() => { this.callback(detail) }, 400); } }
onLoad() { Throttle.init(this.uploadData, 400) // 初始化 }
onSearch({ detail }) { // detail 是頁面傳過來的數據,不需要的可以刪掉
Throttle.search(detail) // 調用防抖函數
},
我這個需求是搜索功能的防抖,經驗證也是可以的。
總結: 函數防抖的實現方法比較多,這里的例子使用的是最簡單的,其他請各位自行搜索吧。
