在开发小程序的时候会出现这样一种情况:当网络条件差或其他情况下,使用者会认为点击无效而进行多次点击,最后出现多次触发点击事件的情况:
解决办法
运用函数节流(throttle):函数在一段时间内多次触发只会执行第一次,在这段时间结束前,不管触发多少次也不会执行函数。
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.apply(this, arguments) //将this和参数传给原函数
_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触发一次。
参考
微信小程序:防止多次点击跳转(函数节流)_极乐叔的博客-CSDN博客_微信小程序throttle
微信小程序:防止多次点击跳转(函数节流)-教程-小程序社区-微信小程序-微信小程序开发社区-小程序开发论坛-微信小程序联盟