js实现防抖,节流

防抖函数。

  将几次操作合并为一次操作进行。设置一个计时器,规定在延迟时间后触发函数,但是在延迟时间内如果再次触发,就会取消之前的计时器。如此,只有最后一次操作能触发。代码如下:

function debounce(fn,wait){
     let timer=null;
     return function(){
          let args=arguments,that=this;
          timer&&clearTimeout(timer);
          timer=setTimeout(function(){fn.apply(that,args)},wait)
     }        
} 

节流函数。

  一定时间内只触发一次函数。并且开始触发一次,结束触发一次。代码如下:

function throttle(fun, delay){
  let timer = null;
  let startTime = Date.now();
  return function(){
    let curTime = Date.now();
    let remain = delay - (curTime - startTime);
    let that = this;
    let args = arguments;
    clearTimeout(timer);
    if(remain <= 0){
      fun.apply(that,args);
      startTime = Date.now();
    }else{
      timer = setTimeout(fun, remain);
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/wjgoblin/p/10950886.html