Debounce & Throttle
Debounce & Throttle
最完整,必看,https://css-tricks.com/debouncing-throttling-explained-examples/
有很多視覺化的 demo
一般的 scroll 觸發頻率有可能達一秒三十次,在手機上甚至達到一秒一百次
一句話說清楚,Debounce 就是把連續觸發的許多事件,只當作一次事件。
實作上,可以是「立即觸發,忽略後面連續的一串事件」,也可以是「等一串事件發生後,只觸發一次」
在 Lodash 就是 leading 和 trailing OPTIONS
用得上的情境很多:視窗調整大小,keypress on autocomplete,資料驗證的提示
作者建議直接使用 underscore 或 Lodash 的 code,並教你怎麼只取出你需要的那 2KB 的 code
使用時常犯的錯誤
一句話說清楚,Throttle 就是確保每段間隔時間內只執行一次
使用情境:無限捲動載入內容
一句話說清楚,傳統的視覺更新常常用 setTimeout 或 setInterval,你可以改用原生的 requestAnimationFrame 來重繪畫面、更新動畫
可以把它想成是有特殊用途的 Throttle
缺點
我們要自己管理 start/cancelation of rAFs,不像 .debounce 或 .throttle 都內建幫你處理好
瀏覽器該分頁如果不是 active 就不會執行。Although for scroll, mouse or keyboard events this doesn't matter
在 IE9, Opera Mini and old Android 中不支援(文章日期:2016.04.06)。(A polyfill [http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/\
在 Node.js 中不支援,所以無法用來處理 filesystem events
一個捲動 Debounce 的實例
視覺化小例子,精簡快速結論,http://jsfiddle.net/missinglink/19e2r2we/
Lodash 的 Debounce 與 throttle,https://lizhiyao.github.io/2017/02/15/debounce-throttle/
簡中,讀起來比較快。有簡單的程式
Last updated