知識
不管是網(wǎng)站,軟件還是小程序,都要直接或間接能為您產(chǎn)生價值,我們在追求其視覺表現(xiàn)的同時,更側(cè)重于功能的便捷,營銷的便利,運(yùn)營的高效,讓網(wǎng)站成為營銷工具,讓軟件能切實提升企業(yè)內(nèi)部管理水平和效率。優(yōu)秀的程序為后期升級提供便捷的支持!
您當(dāng)前位置>首頁 » 新聞資訊 » 小程序相關(guān) >
微信小程序:防止多次點擊跳轉(zhuǎn)(函數(shù)節(jié)流)
發(fā)表時間:2021-3-31
發(fā)布人:葵宇科技
瀏覽次數(shù):92
場景
在使用小程序的時候會出現(xiàn)這樣一種情況:當(dāng)網(wǎng)絡(luò)條件差或卡頓的情況下,使用者會認(rèn)為點擊無效而進(jìn)行多次點擊,最后出現(xiàn)多次跳轉(zhuǎn)頁面的情況,就像下圖(快速點擊了兩次):
解決辦法
然后從 輕松理解JS函數(shù)節(jié)流和函數(shù)防抖 中找到了解決辦法,就是函數(shù)節(jié)流(throttle):函數(shù)在一段時間內(nèi)多次觸發(fā)只會執(zhí)行第一次,在這段時間結(jié)束前,不管觸發(fā)多少次也不會執(zhí)行函數(shù)。
/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觸發(fā)一次。
但是這樣的話出現(xiàn)一個問題,就是當(dāng)你想要獲取this.data
得到的this
是undefined
, 或者想要獲取微信組件button
傳遞給點擊函數(shù)的數(shù)據(jù)e
也是undefined
,所以throttle
函數(shù)還需要做一點處理來使其能用在微信小程序的頁面js
里。
出現(xiàn)這種情況的原因是throttle
返回的是一個新函數(shù),已經(jīng)不是最初的函數(shù)了。新函數(shù)包裹著原函數(shù),所以組件button
傳遞的參數(shù)是在新函數(shù)里。所以我們需要把這些參數(shù)傳遞給真正需要執(zhí)行的函數(shù)fn
。
最后的throttle
函數(shù)如下:
function throttle(fn, gapTime) {
if (gapTime == null || gapTime == undefined) {
gapTime = 1500
}
let _lastTime = null
// 返回新的函數(shù)
return function () {
let _nowTime = + new Date()
if (_nowTime - _lastTime > gapTime || !_lastTime) {
fn.apply(this, arguments) //將this和參數(shù)傳給原函數(shù)
_lastTime = _nowTime
}
}
}
再次點擊按鈕this
和e
都有了:
參考
- 輕松理解JS函數(shù)節(jié)流和函數(shù)防抖
源代碼
- tomfriwel/MyWechatAppDemo 的
throttle
頁面
相關(guān)案例查看更多
相關(guān)閱讀
- 汽車報廢回收管理系統(tǒng)
- 開發(fā)微信小程序
- 百度小程序開發(fā)公司
- 昆明網(wǎng)站開發(fā)
- 云南網(wǎng)站建設(shè)百度
- 電商網(wǎng)站建設(shè)
- 云南網(wǎng)站建設(shè) 網(wǎng)絡(luò)服務(wù)
- 網(wǎng)站建設(shè)優(yōu)化
- 報廢車回收管理系統(tǒng)
- 網(wǎng)站排名
- 旅游網(wǎng)站建設(shè)
- python開發(fā)小程序
- 網(wǎng)站優(yōu)化哪家好
- 小程序制作
- 汽車報廢管理
- 微信分銷
- 云南網(wǎng)站制作
- 網(wǎng)站建設(shè)專業(yè)品牌
- 貴州小程序開發(fā)
- 云南小程序設(shè)計
- web
- 云南網(wǎng)站建設(shè)案例
- 網(wǎng)站制作
- 網(wǎng)站建設(shè)哪家強(qiáng)
- 網(wǎng)站建設(shè)價格
- 云南小程序開發(fā)費用
- 云南網(wǎng)站設(shè)計
- 網(wǎng)站收錄
- 網(wǎng)站搭建
- web開發(fā)技術(shù)