最的小程序遇到按钮快速点击时会执行多次,有时间会导致页面被打开多次。
本篇文章记录一下微信小程序能过截流函数控制按钮被点击多次的问题
创建util.js文件,这里面都是帮助类的函数
/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 = { throttle }
使用方法
wxml代码
<button bindtap='onTap'>快速点击</button>
js代码
const util = require('../../utils/util.js')
Page({
// 多次点击的间隔时间 大于2秒 才会执行
tap: util.throttle(function (e) {
console.log(this)
console.log(e)
}, 2000)
})