防抖和节流函数

防抖函数解决的问题:

防止误操做等屡次输出点击等事件形成的屡次通讯请求。


防抖代码以下:

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中调用:

<button onclick="throttle(clickFun)()">节流点击</button>
function clickFun(){
alert(''点击");
}

TODO:下次将写一篇关于前端性能优化的文章(三方面:通信优化、首屏渲染优化、界面操做性能优化)

相关文章
相关标签/搜索