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

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


封装的第二种
function throttle(me, key, fn, delay = 1000) {
  let pre = me.data[key]
  return function () {
  let now = + new Date();
  if (now - pre >= delay) {
    fn.apply(me, arguments)
    pre = now
    me.setData({
      [key]: now
    })
  }
 }
}
 

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

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


// 第二种
myclick: function (e) {
        let that = this
        throttle(that, 'pre', function(){
        console.log(111111111111)
}, 1000)() },

  

原文地址:https://www.cnblogs.com/Alitar/p/11975001.html