js 消抖(debounce)與節流(throttle)

概念

debounce 和 throttle 都是用來減小事件觸發的頻率,用來減小服務器請求壓力,優化頁面。服務器

debounce 實現

// 接受一個函數並返回一個debounce函數
 function debounce(func, wait) {
    let timerId
    return function(...args) {
       timerId && clearTimeout(timerId)
       timerId = setTimeout(() => {
          func.apply(this, args)
       }, wait)
    }
 }

throttle 實現1

// 接受一個函數並返回一個throttle函數
function throttle(func, wait = 100) {
   let timerId
   let start = Date.now()
   return function(...args) {
     const curr = Date.now()
     clearTimeout(timerId)
     if (curr - start >= wait) {// 能夠保證func必定會被執行
       func.apply(this, args)
       start = curr
     } else {
       timerId = setTimeout(() => {
         func.apply(this, args)
       }, wait)
    }
  }
}

throttle 實現2

function throttle(func, wait = 100){
    let disabled = false
    return function(...args) {
       if(valid){
           return false 
       }
       disabled = true
       setTimeout(() => {
            func.apply(this, args)
            disabled =false;
        }, delay)
    }
}

兩種方法有些許區別,以點鍵盤輸入事件爲例,第一種方法事件觸發次數總會比第二種多一次,可是避免最後一次輸入完無響應的狀況。app

對比

debounce(去抖)和 throttle(節流)的對比,單純的從中文名字理解比較難理解區別,中文是英譯過來的。
去抖能夠理解爲去抖延時,事件只會在調用完,必定時間間隔後被觸發,有一種延時的效果。
節流能夠理解爲節流降速,在規定時間內,無論動做調用多少次,只發一次動做,下降動做頻率。函數

打個小比方。若是有一天你看一個網站不爽,你想手動增長他的服務器載荷,因而你使勁的點他的搜索按鈕,碰巧你又是一個精力充沛的小夥,以每秒一次手速,點擊了24個小時。
這個時候若是對方使用了debounce技術,間隔是2s,你會發現你點了一天一晚上,最後只請求了一次,是在最後一次點擊2s以後發生。
若是對方使用了throttle技術,間隔也是2s,那麼請求次數就是24x60x60/2次,無論你點擊速度多快,它老是2s請求一次,很平穩。優化

相關文章
相關標籤/搜索