1. 程式人生 > >效能優化之throttle, debounce

效能優化之throttle, debounce

throttle節流的思想:

應用場景:

主要用在scroll , resize景中。在瀏覽器中像mousemove,mouseenter,scroll,resize 這類事件會頻繁的觸發,如果不作截流設定效能會極大下降。

 const throttle = (func, limit) => {
      let lastFunc
      let lastRan
      return function() {
        const context = this
        const args = arguments
        if (!lastRan) {
          func.apply(context, args)
          lastRan = Date.now()
        } else {
          clearTimeout(lastFunc)
          lastFunc = setTimeout(function() {
            if ((Date.now() - lastRan) >= limit) {
              func.apply(context, args)
              lastRan = Date.now()
            }
          }, limit-(Date.now() - lastRa))
        }
      }
    }
  

debounce:防抖的思想:

    const  debounce  = (fn,delay)=>{
        let timer ;
        delay = delay || 200
        return function(){
          let ctx = this
          let args = arguments
          if(timer) clearTimeout(timer)
          timer = setTimeout(()=>{
             fn.apply(ctx,args)
          },delay)
        }  
    }

應用場景:

主要用在百度首頁的輸入聯想詞請求中。如果每輸入一個字就向後臺傳送請求,會造成請求的極大浪費。因為最終我們想要的結果是最後輸入的欄位所匹配出來的結果。

以下是測試地址:

Demo地址: