vue 函数节流

背景:

  今天客户在测试的时候,我发现了一个问题,那就是,客户喜欢连续点击一个按钮,这时就会出现很多问题,最大的问题就是前段的ajax并发问题,因为客户的连续点击,同时发送多个请求,如果前面的请求响应比后面的请求响应的时间晚,前面的数据就会覆盖后面的数据,这也是一个常见的问题吧

解决方案:

使用大家众所周知的解决办法,函数节流

函数的节流,应该是个学JS的应该就知道,当初的阿里的月饼门事件.. 就不多说了

首先需要定义一个周期延迟函数,记得定义定时器句柄

data () {
    return {
      // 设置定时器的句柄,用来缓存的
      timer: null
    };
  },
fnThrottle (method, delay, duration) {
        var that = this;
        var timer = this.timer;
        var begin = new Date().getTime();
        return function(){
          var context = that;
          var args = arguments;
          var current = new Date().getTime();
          clearTimeout(timer);
          if(current-begin>=duration){
            method.apply(context,args);
            begin=current;
          }else{
            console.log(delay)
            that.timer=setTimeout(function(){
              method.apply(context,args);
            },delay);
          }
        }
      }

然后重复定义一个执行函数

nextMat2:function(){
        this.fnThrottle(this.nextMat, 1000, 1000)();
      },

而nextMat就是真实执行函数

 nextMat:function() {
    console.log("我是真实执行函数")      
}

然后在上面的标签中指定为执行函数就可以了

节流的时间按需求指定

当然这只是一个简单粗暴的方法,具体的功能模块化什么的,由大家自己优化

作者:彼岸舞

时间:20201029

内容关于:工作中用到的小技术

本文来源于网络,只做技术分享,一概不负任何责任

原文地址:https://www.cnblogs.com/flower-dance/p/13897806.html