理解JS的節流、防抖及使用場景
阿新 • • 發佈:2019-02-10
函式防抖(debounce)
在事件被觸發n秒後再執行回撥,如果在這n秒內又被觸發,則重新計時。
//模擬一段ajax請求 function ajax(content) { console.log('ajax request ' + content) } function debounce(fun, delay) { return function (args) { let that = this let _args = args clearTimeout(fun.id) fun.id = setTimeout(function () { fun.call(that, _args) }, delay) } } let inputb = document.getElementById('debounce') let debounceAjax = debounce(ajax, 500) inputb.addEventListener('keyup', function (e) { debounceAjax(e.target.value) }) 作者:薄荷前端 連結:https://juejin.im/post/5b8de829f265da43623c4261 來源:掘金 著作權歸作者所有。商業轉載請聯絡作者獲得授權,非商業轉載請註明出處。
個人理解 函式防抖就是法師發技能的時候要讀條,技能讀條沒完再按技能就會重新讀條。
函式節流(throttle)
規定在一個單位時間內,只能觸發一次函式。如果這個單位時間內觸發多次函式,只有一次生效。
function throttle(fun, delay) { let last, deferTimer return function (args) { let that = this let _args = arguments let now = +new Date() if (last && now < last + delay) { clearTimeout(deferTimer) deferTimer = setTimeout(function () { last = now fun.apply(that, _args) }, delay) }else { last = now fun.apply(that,_args) } } } let throttleAjax = throttle(ajax, 1000) let inputc = document.getElementById('throttle') inputc.addEventListener('keyup', function(e) { throttleAjax(e.target.value) })
個人理解 函式節流就是fps遊戲的射速,就算一直按著滑鼠射擊,也只會在規定射速內射出子彈。
總結
- 函式防抖和函式節流都是防止某一時間頻繁觸發,但是這兩兄弟之間的原理卻不一樣。
- 函式防抖是某一段時間內只執行一次,而函式節流是間隔時間執行。
結合應用場景
- debounce
- search搜尋聯想,使用者在不斷輸入值時,用防抖來節約請求資源。
- window觸發resize的時候,不斷的調整瀏覽器視窗大小會不斷的觸發這個事件,用防抖來讓其只觸發一次
- throttle
- 滑鼠不斷點選觸發,mousedown(單位時間內只觸發一次)
- 監聽滾動事件,比如是否滑到底部自動載入更多,用throttle來判斷