vue 节流和防抖

防抖

  按钮频繁被点击,同一个接口在某个时间段内多次被访问,比如搜索。防抖的目的是,触发事件后,在固定时间之后调用事件。如果在设置时间以内,再次触发事件,就清除定时器,重新开始计时。直至固定时间内没有再次触发事件,才去执行设置的函数。

  

   let timer = null
    Vue.prototype.delay =  function(method, delay) {
      var context = this
      return function (){
        var args = arguments
        if (timer) {
          clearTimeout(timer)
        }
        timer = setTimeout(function(){
          method.apply(context, args)
        }, delay)
      }
    }
    export default {
        methods:{
            fn() {
                  delay(() => {
                    //执行部分
                  }, 500)()
         //  this.delay返回的是function,还没被调用的,所以要用()来调用函数
 } } }

节流
  高频率触发事件,比如滚动至顶部。设置某个时间段内访问几次设置的函数
var timer = null;    
var throttle = function(func, delay) {
    return function() {                
        var context = this;               
        var args = arguments;                
        if (!timer) {                    
            timer = setTimeout(function() {                        
                func.apply(context, args);                        
                timer = null;                    
            }, delay);                
        }            
    }        
}        
function handle() {            
    console.log(Math.random());        
}        
window.addEventListener('scroll', throttle(handle, 1000));

别人的demo:
https://wall-wxk.github.io/blogDemo/2017/02/15/throttleAndDebounce.html
 
原文地址:https://www.cnblogs.com/ch-zaizai/p/13955033.html