微信小程序函数节流(防止多次点击,可用于“立即支付,页面跳转等”)

函数节流(throttle):函数在一段时间内多次触发只会执行第一次,在这段时间结束前,不管触发多少次也不会执行函数。

 1.添加utils.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
}

 2.在需要使用的页面引入utils.js

const util = require('../../utils/util.js')

 使用

 handle: util.throttle(function () {
     
    })

  

猜你喜欢

转载自www.cnblogs.com/Glant/p/11423359.html