防抖和節流函數

防抖函數解決的問題:

防止誤操做等屢次輸出點擊等事件形成的屢次通訊請求。


防抖代碼以下:

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:下次將寫一篇關於前端性能優化的文章(三方面:通信優化、首屏渲染優化、界面操做性能優化)

相關文章
相關標籤/搜索