← 中文资源

简体中文版本

Lodash 防抖与节流处理高频事件

用 Lodash 的 debounce 与 throttle 处理滚动与输入等高频事件:控制首尾沿触发时机,maxWait 兜底,句柄可取消与冲刷。

阅读英文原文

示例说明

搜索框每敲一个字符就发请求、滚动监听每秒触发几十次回调,都会造成资源浪费。debounce 把连续调用合并为停止后的一次执行,适合自动保存与搜索联想;throttle 保证固定间隔至多执行一次,适合滚动打点。leading 与 trailing 决定触发发生在时间窗的开头还是结尾。

技术要点

  • debounce 合并连续调用为最终一次
  • maxWait 防止连续输入无限推迟保存
  • cancel 与 flush 服务组件卸载场景

代码解读

saveDraft 配置 trailing 触发,三次快速调用只会保存最后一次内容;maxWait 保证内容再怎么持续编辑,最多 3 秒也会落盘一次。onScroll 用 leading 触发让第一次滚动立即响应。卸载前 cancel 阻止已销毁组件的回调,flush 立即执行挂起的保存。

使用建议

滚动监听务必声明 passive 提升渲染性能。防抖保存场景要在页面卸载时 flush,否则最后一次编辑丢失。周期与业务时延要求对齐,别照抄常见默认值。

代码示例

import { debounce, throttle } from 'lodash-es';

const saveDraft = debounce(
  (content) => {
    console.log('autosaving draft of', content.length, 'chars');
  },
  800,
  { leading: false, trailing: true, maxWait: 3000 },
);

saveDraft('first edit');
saveDraft('second edit');
saveDraft('third edit');

const onScroll = throttle(
  () => console.log('scroll checkpoint at', window.scrollY),
  200,
  { leading: true, trailing: false },
);

document.addEventListener('scroll', onScroll, { passive: true });

window.addEventListener('beforeunload', () => {
  saveDraft.cancel();
  onScroll.cancel();
});

saveDraft.flush();