JS 特效 词条目录
前端Wiki/JS 特效/基础/性能与优化

防抖与节流

防抖(debounce):事件连续触发时只执行最后一次——搜索框输入联想、窗口 resize 重算布局。节流(throttle):固定间隔最多执行一次——滚动监听、鼠标移动,防止高频事件拖垮性能。

两者都是“控制函数执行频率”的工具。滚动特效里 90% 的卡顿都源于 scroll 监听里直接算重逻辑——套上节流(或改用 rAF/IntersectionObserver)立刻流畅。

  • 防抖:等用户停下来再执行(输入框联想)
  • 节流:每 N 毫秒最多一次(滚动、mousemove)
  • scroll 高频回调用 rAF 节流是社区标准做法
HTML
<style>
#box { max-width: 340px; margin: 20px auto; }
#log { height: 110px; overflow: auto; background: #0d1117; color: #e6edf3;
       border-radius: 8px; padding: 10px; font: 12px Consolas,monospace; }
#log div { padding: 2px 0; }
</style>
<div id="box">
  <button id="db" style="padding:8px 18px">狂点我(防抖 500ms)</button>
  <div id="log"></div>
</div>
<script>
function log(msg) {
  var d = document.createElement('div');
  d.textContent = new Date().toLocaleTimeString() + ' ' + msg;
  document.getElementById('log').appendChild(d);
}
function debounce(fn, wait) {
  var t; return function () {
    clearTimeout(t); t = setTimeout(fn, wait);
  };
}
document.getElementById('db').addEventListener('click',
  debounce(function () { log('防抖:只执行这一次'); }, 500));
// 节流演示:滚动这里每 200ms 最多记一条
var throttle = function (fn, gap) {
  var last = 0; return function () {
    var now = Date.now();
    if (now - last > gap) { last = now; fn(); }
  };
};
document.getElementById('log').addEventListener('scroll', throttle(function () {
  log('滚动事件已节流'); }, 200));
</script>
本节要点防抖 = 只执行最后一次(输入),节流 = 固定频率执行(滚动);高频事件必加。
🔗 相关词条事件DOMJavaScript