場景
在使用小程序的時候會出現這樣一種情況:當網絡條件差或卡頓的情況下,使用者會認為點擊無效而進行多次點擊,最后出現多次跳轉頁面的情況,就像下圖(快速點擊了兩次):
解決辦法
然后從 輕松理解JS函數節流和函數防抖 中找到了解決辦法,就是函數節流(throttle):函數在一段時間內多次觸發只會執行第一次,在這段時間結束前,不管觸發多少次也不會執行函數。
/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)
})
這樣,瘋狂點擊按鈕也只會1s觸發一次。
但是這樣的話出現一個問題,就是當你想要獲取this.data
得到的this
是undefined
, 或者想要獲取微信組件button
傳遞給點擊函數的數據e
也是undefined
,所以throttle
函數還需要做一點處理來使其能用在微信小程序的頁面js
里。
出現這種情況的原因是throttle
返回的是一個新函數,已經不是最初的函數了。新函數包裹着原函數,所以組件button
傳遞的參數是在新函數里。所以我們需要把這些參數傳遞給真正需要執行的函數fn
。
最后的throttle
函數如下:
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.apply(this, arguments) //將this和參數傳給原函數 _lastTime = _nowTime } } }
再次點擊按鈕this
和e
都有了:
參考
源代碼
- tomfriwel/MyWechatAppDemo 的
throttle
頁面
轉 : http://www.wxapp-union.com/portal.php?mod=view&aid=3618
https://blog.csdn.net/rolan1993/article/details/79170513