下面的兩個都是立即執行版:
// debounce 防抖 function debounce (fn,immediate) { var timer; return function() { if(timer) clearTimeout(timer); immediate && !timer && fn(); // 首次進入,立即執行(立即執行開啟,定時器沒開啟) timer = setTimeout(() => { timer = null; }, 1000) } } // throttling 節流 function throttling(fn,immediate) { var timer; return function () { if (timer) return false; !timer && immediate && fn(); timer = setTimeout(() => { timer = null; }, 1000) } } document.getElementById("btn").onclick = throttling(function () { console.log(1) },true)
總結: 可以發現防抖節流的區別在於 一開始的判斷定時器存在所做的處理,防抖是清除定時器重新來,節流是 return false 等待定時器自動清除。