两者都是给高频事件「降温」的手段,场景不同:搜索框 input 用防抖(用户敲完手再请求),滚动监听 scroll 用节流(每 200ms 算一次位置)。防抖是「等人说完话」,节流是「固定节奏采样」,一字之差。
手写是高频面试题。防抖的核心是「清上一次的定时器」;节流的核心是「用时间戳判断是否越过间隔」。两者都用闭包持有 timer/last 变量,也都能加 immediate 选项让首次立即执行。
// 防抖:触发后等 300ms 没有新触发才真正执行 function debounce(fn, ms) { let timer = null; // 闭包保存定时器 return function (...args) { clearTimeout(timer); // 关键:每次都清掉上一次 timer = setTimeout(() => fn.apply(this, args), ms); }; } // 节流:每 300ms 最多放行一次 function throttle(fn, ms) { let last = 0; return function (...args) { const now = Date.now(); if (now - last >= ms) { last = now; fn.apply(this, args); } }; } const onSearch = debounce(q => console.log('请求:', q), 300); const onScroll = throttle(() => console.log('位置:', scrollY), 200);