防抖与节流

防抖(debounce):

 目的是为了让一定事件段连续的函数调用,只让其执行一次。(个人在工作中用到在搜索发起请求中会用的到些)

function debounce(handler,delay){
     var timer = null;
     return function(){
           var self  =  this;
           var args = arguments;
           clearTimeout(timer)
           timer = setTimeout(function(){
                handler.apply(self,args)
           },delay)
    }
}

节流(throttle):

目的是让一个函数不要执行太频繁,减少一些过快的调用。(个人用的话在按钮重复点击上)

function throttle (handler,wait) {
     var lastTime = 0;
     return function () {
       var nowTime = new Date().getTime();

        if (nowTime - lastTime > wait){
              handler.apply(this,arguments);
              lastTime = nowTime
          }
     }
}

 

 

 

 

posted @ 2020-05-07 15:10  心之所指,行之所至  阅读(98)  评论(0)    收藏  举报