節流和防抖動

原由

面試被問到了節流和防抖動, 本身對這兩個的概念比較模糊, 都不知道回答了什麼鬼css

從語文和英語學起

首先, 先看字面意思:
節流(throttle)的意思就是水龍頭關小點, 頻率不要那麼高
防抖動(debounce), 這根彈簧, 你不要來回蹦了, 我就要你最後停下來的沒有發生形變的那一刻git

舉個例子

節流: 在改變窗口大小的時候, resize事件會觸發. 可能窗口大小變化了一下就觸發了幾十次事件, 但我但願就只觸發那麼十幾回事件 , 這就叫節流.
防抖動: 在改變窗口大小的時候, resize事件會觸發. 可能窗口大小變化了一下就觸發了幾十次事件, 但我但願只有在大小改變完(通過必定長的時間), 才觸發一次事件 , 這就叫防抖動github

簡單的實現

雖然上面說了那麼多, 但好像還不是很懂怎麼用啊, 怎麼寫啊? 那就搜搜別人的博客和一些成熟的庫看他們是怎麼設計這個函數以及使用的面試

throttle

throttle(func, [wait=0])
Creates a throttled function that only invokes func at most once per every wait milliseconds(throttle方法返回一個函數, 在wait毫秒裏, 這個函數最多隻會調用一次func)

參數和返回值都知道了, 那就寫吧app

function throttle (func, wait = 0) {
  let timer
  let start
  let now

  return function () {
    const ctx = this
    const args = arguments
    now = new Date().getTime()
    // 若是不是第一次, 而且時間間隔尚未過去wait毫秒
    if (start && now - start < wait) {
      if (timer) {
        clearTimeout(timer)
      }
      timer = setTimeout (() => {
        func.apply(ctx, args)
        start = now
      }, wait)
    } else {
      func.apply(ctx, args)
      start = now
    }
  }
}

debounce

debounce(func, [wait=0])
Creates a debounced function that delays invoking func until after wait milliseconds have elapsed since the last time the debounced function was invoked(debounce方法返回一個函數, 這個函數的調用func的間隔, 至少隔了wait毫秒)
function debounce (func, wait = 0) {
  let timer

  return function () {
    const ctx = this
    const args = arguments
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      func.apply(ctx, args)
    }, wait)
  }
}

應用與實踐

到這裏, 單單看代碼的話, throttle和denounce也是賊像. 仍是要應用多了才能更深刻地理解的. 然而本身應用上也是淺薄, 仍是安利一下別人的文章吧, Debouncing and Throttling Explained Through Examples, 中文翻譯函數

其餘的參考文章:
分析_的.debounce和.throttle
Debounce 和 Throttle 的原理及實現this

相關文章
相關標籤/搜索