zoukankan      html  css  js  c++  java
  • 节流函数(防止重复请求)小程序

    先在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)() },

      

  • 相关阅读:
    ZOJ 3556
    ZOJ 2836
    HDU 2841
    HDU 4135
    POJ 3695
    POJ 2773
    HDU 4407
    HDU 1796
    ZOJ 3688
    ZOJ 3687
  • 原文地址:https://www.cnblogs.com/Alitar/p/11975001.html
Copyright © 2011-2022 走看看