一圖秒懂函式防抖和函式節流
函式防抖(debounce)和函式節流(throttle)都是為了緩解函式頻繁呼叫,它們相似,但有區別

如上圖,一條豎線代表一次函式呼叫, 函式防抖 是間隔超過一定時間後才會執行, 函式節流 是一定時間段內只執行一次。
函式防抖實現
function debounce(fn, delay) { let timer = null; return function () { if (timer) clearTimeout(timer); timer = setTimeout(() => { fn.apply(this, arguments); }, delay); } } 複製程式碼
函式節流實現
function throttle(fn, cycle) { let start = Date.now(); let now; let timer; return function () { now = Date.now(); clearTimeout(timer); if (now - start >= cycle * 1000) { fn.apply(this, arguments); start = now; } else { timer = setTimeout(() => { fn.apply(this, arguments); }, cycle); } } } 複製程式碼
lodash
對這兩個方法的實現更靈活一些,有第三個引數,可以去參觀學習。