1. 概念上的區別(從 handle 的有效性分析)
- 防抖:多次執行只有最后一次生效,必要引數 [handle, time]
- 節流:一段時間內只能執行一次,必要引數 [handle, time]
2. 實作一下
- 防抖:
1 function debounce(handle, time) { 2 let timer = null; 3 return function () { 4 if (timer) { 5 clearTimeout(timer); 6 timer = null; 7 } 8 timer = setTimeout(() => { 9 handle(); 10 }, time); 11 }; 12 }
- 節流:
1 function throttle(handle, time) { 2 let timer = null; 3 return function () { 4 if (!timer) { 5 handle(); 6 timer = setTimeout(() => { 7 clearTimeout(timer); 8 timer = null; 9 }, time); 10 } 11 }; 12 }
3. 從執行堆疊與事件佇列的角度深度分析
-
防抖是執行了唯一一個被添加到事件佇列的 handle,它前面的 handle 隨著計時器的移除也都沒有進入事件佇列,也就不存在進入執行堆疊了
-
節流是 handle 在當前執行堆疊就直接執行了
- 所以,防抖是在下一次執行堆疊執行,節流是在當前執行堆疊執行
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/526900.html
標籤:JavaScript
