防抖和节流函数

防抖函数

解决的问题:防止误操作等多次输出点击等事件造成的多次通信请求。

防抖代码如下:

const debounce = (fn, delay = 1000) => {
  let timer = null;
  return (...args) => {
    console.log(`clear timer:`, this.timer);  //必须要写this.
    console.log(`_that===this :`, _that === this);
    clearTimeout(this.timer);
    this.timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
    console.log(`timer value:`, this.timer);
  };
};

html中调用

 <button onclick="debounce(clickFun)()">防抖点击</button>
function clickFun(){
alert(''点击");
}

## 节流函数 #### 解决的问题:当dom布局频繁Resize时需要使用节流函数减少回流或重绘的次数。 ### 节流函数代码如下: ``` const throttle=(fn,delay=1000)=>{ let flag=false; return (...args)=>{ if(this.flag)return; this.flag=true; setTimeout(() => { fn.apply(this,args); this.flag=false; }, delay); } } ``` ### html中调用: ``` function clickFun(){ alert(''点击"); } ```
posted @ 2019-11-20 19:06  我是马赛克  阅读(210)  评论(0编辑  收藏  举报