理解節流與防抖
節流 Throttling
節流限制了一個函式可以在短時間內被呼叫的次數。可以這樣形容:在一毫秒內最多執行此函式 1 次。
Throttling enforces a maximum number of times a function can be called over time. As in "execute this function at most once every 100 milliseconds."
再換句話說:
節流會忽略在短時間內高頻發生的事件,只按照計劃好的頻率觸發。
//fn 要執行的函式 //delay 計劃好的執行間隔 //返回一個函式 function throttled(fn, delay) { let lastCall = 0;//初始化lastCall return function (...args) { const now = (new Date).getTime();//當函式被執行,獲取當前時間 if (now - lastCall < delay) { //這裡(now - lastCall)就是間隔時間 return;//如果間隔時間小於計劃好的執行間隔,什麼也不做。 } lastCall = now; //更新lastCall return fn(...args); } }
防抖 Debouncing
防抖確保了一個函式只有在一個固定時間段內沒有被呼叫過後,才會再次被呼叫。可以這樣形容:比如說只有在 1 毫秒過後,才允許執行這個函式。
Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called."
再換句話說:
防抖會等待事件不再高頻發生,再觸發。
//fn 要執行的函式 //delay 計劃好的等待時間 //返回一個函式 function debounced(delay, fn) { let timerId; return function (...args) { if (timerId) {//如果正在一個timeout中 clearTimeout(timerId);//中斷timeout,不會發生setTimeout的回撥函式 } timerId = setTimeout(() => {//開始新的timeout fn(...args); timerId = null; }, delay); } }
結論
節流在我們不關心函式引數 是什麼的時候比較有用,比如滑鼠移動,滾輪事件,我們在乎的是操作的頻率。
防抖在我們關心高頻事件發生過後,得到的那個結果 的時候,比較有用,比如使用者迅速輸入完一串使用者名稱,對其進行查重的結果。
這個網站 很好的可視化了節流與防抖。
參考資訊
The Difference Between Throttling and Debouncing
Understanding Throttling and Debouncing