一道筆試題:利用JS代碼實現防抖和節流
防抖 (Debounce)
防抖的目的是在一系列連續的調用中,只有在最后一次調用后的一段時間內沒有新的調用才會執行該函數。這對于一些需要在用戶停止操作后才執行的場景非常有用,比如輸入框的搜索建議。
function debounce(func, wait) { let timeout; return function() { const context = this; const args = arguments; clearTimeout(timeout); timeout = setTimeout(function() { func.apply(context, args); }, wait); }; }
節流 (Throttle)
節流的目的是保證一個函數在一定時間內只被調用一次。這可以確保函數不會因為高頻觸發而消耗過多資源。例如,當用戶滾動頁面時,我們可能只想每隔一段時間才更新數據。
function throttle(func, limit) { let inThrottle; return function() { const args = arguments; const context = this; if (!inThrottle) { func.apply(context, args); inThrottle = true; setTimeout(function() { inThrottle = false; }, limit); } }; }
// 使用防抖 const debouncedFunction = debounce(function() { console.log('This will be logged after 500ms of silence.'); }, 500); window.addEventListener('resize', debouncedFunction); // 使用節流 const throttledFunction = throttle(function() { console.log('This will be logged at most once every second.'); }, 1000); window.addEventListener('scroll', throttledFunction);
像這種基本的而且常用的知識還是挺容易考的

浙公網安備 33010602011771號