节流函数(防止重复请求)小程序

先在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 }

在需要的页面的js文件引入  var util = require('')

tap: util.throttle(function (e) {
 //需要自行的函数
}, 1000)   //  1000间隔时间

  

猜你喜欢

转载自www.cnblogs.com/Alitar/p/11975001.html