场景
在使用小程序的时候会出现这样一种情况:当网络条件差或卡顿的情况下,使用者会认为点击无效而进行多次点击,最后出现多次跳转页面的情况,就像下图(快速点击了两次):
解决办法
然后从 轻松理解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.apply(this, arguments) //将this和参数传给原函数
_lastTime = _nowTime
}
}
}
module.exports = {
formatTime: formatTime,
RandNum: RandNum,
showLoading: showLoading,
hideLoading: hideLoading,
ajaxPost: ajaxPost,
ajaxGet: ajaxGet,
share:share,
isLogin: isLogin,
throttle: throttle,
}
/pages/topic/sendQapage.wxml
<button class="header_sendBtn" bindtap="formSubmit">发布</button>
/pages/topic/sendQapage.js
//发布问题回答
formSubmit: util.throttle(function(e) {
console.log(this)
console.log(e)
console.log((new Date()).getSeconds())
},10000),
这样,疯狂点击按钮也只会10s触发一次。