微信小程序:防止多次點擊跳轉(函數節流)
發表時(shí)間:2021-3-31
發布人(rén):融晨科技
浏覽次數:94
場景
在(zài)使用小程序的(de)時(shí)候會出(chū)現這(zhè)樣一種情況:當網絡條件差或卡頓的(de)情況下,使用者會認爲(wéi / wèi)點擊無效而(ér)進行多次點擊,最後出(chū)現多次跳轉頁面的(de)情況,就(jiù)像下圖(快速點擊了(le/liǎo)兩次):
解決辦法
然後從 輕松理解JS函數節流和(hé / huò)函數防抖 中找到(dào)了(le/liǎo)解決辦法,就(jiù)是(shì)函數節流(throttle):函數在(zài)一段時(shí)間内多次觸發隻會執行第一次,在(zài)這(zhè)段時(shí)間結束前,不(bù)管觸發多少次也(yě)不(bù)會執行函數。
/utils/util.js:
function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn()
_lastTime = _nowTime
}
}
}
module.exports = {
throttle: throttle
}
/pages/throttle/throttle.wxml:
<button bindtap='tap' data-key='abc'>tap</button>
/pages/throttle/throttle.js
const util = require('../../utils/util.js')
Page({
data: {
text: 'tomfriwel'
},
onLoad: function (options) {
},
tap: util.throttle(function (e) {
console.log(this)
console.log(e)
console.log((new Date()).getSeconds())
}, 1000)
})
這(zhè)樣,瘋狂點擊按鈕也(yě)隻會1s觸發一次。
但是(shì)這(zhè)樣的(de)話出(chū)現一個(gè)問題,就(jiù)是(shì)當你想要(yào / yāo)獲取this.data
得到(dào)的(de)this
是(shì)undefined
, 或者想要(yào / yāo)獲取微信組件button
傳遞給點擊函數的(de)數據e
也(yě)是(shì)undefined
,所以(yǐ)throttle
函數還需要(yào / yāo)做一點處理來(lái)使其能用在(zài)微信小程序的(de)頁面js
裏。
出(chū)現這(zhè)種情況的(de)原因是(shì)throttle
返回的(de)是(shì)一個(gè)新函數,已經不(bù)是(shì)最初的(de)函數了(le/liǎo)。新函數包裹着原函數,所以(yǐ)組件button
傳遞的(de)參數是(shì)在(zài)新函數裏。所以(yǐ)我們需要(yào / yāo)把這(zhè)些參數傳遞給真正需要(yào / yāo)執行的(de)函數fn
。
最後的(de)throttle
函數如下:
function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
// 返回新的(de)函數
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments) //将this和(hé / huò)參數傳給原函數
_lastTime = _nowTime
}
}
}
再次點擊按鈕this
和(hé / huò)e
都有了(le/liǎo):
參考
- 輕松理解JS函數節流和(hé / huò)函數防抖
源代碼
- tomfriwel/MyWechatAppDemo 的(de)
throttle
頁面