如何在 JavaScript 中实现防抖和节流?

下面给你最常用、最标准、直接可复制的防抖 & 节流实现,附带使用示例,一看就会。


1. 防抖(Debounce)

原理 :频繁触发时,只在最后一次触发后延迟执行,中间全部忽略。

最简实现

ini 复制代码
function debounce(fn, delay = 300) {
  let timer = null;

  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
}

使用示例(搜索框)

javascript 复制代码
const onSearch = debounce((value) => {
  console.log("请求搜索:", value);
}, 500);

input.addEventListener("input", (e) => {
  onSearch(e.target.value);
});

2. 节流(Throttle)

原理 :固定时间内只执行一次,不管触发多频繁。

时间戳版(立即执行,更常用)

ini 复制代码
function throttle(fn, interval = 300) {
  let lastTime = 0;

  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= interval) {
      fn.apply(this, args);
      lastTime = now;
    }
  };
}

使用示例(滚动)

javascript 复制代码
const handleScroll = throttle(() => {
  console.log("滚动位置", window.scrollY);
}, 300);

window.addEventListener("scroll", handleScroll);

3. 带立即执行的防抖(可选)

有些场景希望第一次立即执行,后面再防抖:

ini 复制代码
function debounceImmediate(fn, delay = 300) {
  let timer = null;

  return function (...args) {
    const isFirst = !timer;

    clearTimeout(timer);
    timer = setTimeout(() => {
      timer = null;
    }, delay);

    if (isFirst) {
      fn.apply(this, args);
    }
  };
}

4. 快速记忆

  • 防抖:等你停手再执行 → 搜索框、输入验证、按钮防重复点击
  • 节流:冷却时间 → 滚动、拖拽、resize、高频点击

需要我给你写一个带取消功能、支持立即执行、兼容 React 的高级版防抖节流吗?

相关推荐
喷火龙8号3 小时前
记一次已推送仓库启用 Git LFS 的完整迁移与验证过程
github
大家的林语冰3 小时前
《前端周刊》React 败北,虾皇登基,OpenClaw 勇夺 GitHub 第一开源软件
前端·javascript·github
ShineWinsu5 小时前
对于Linux:git版本控制器和cgdb调试器的解析
linux·c语言·git·gitee·github·调试·cgdb
zhensherlock5 小时前
Protocol Launcher 系列:Microsoft Edge 浏览器唤起的优雅方案
javascript·chrome·microsoft·typescript·edge·github·edge浏览器
嗡嗡嗡qwq6 小时前
【如何使用vscode+github copilot会更加省额度】
vscode·github·copilot
汪海游龙7 小时前
03.25 AI 精选:Wine 11重写内核层提速跑Windows游戏
github
研究点啥好呢8 小时前
3月24日GitHub热门项目推荐|让AI无所不能
人工智能·python·开源·github
Timer@8 小时前
TypeScript + React + GitHub Actions:我是如何打造全自动化 AI 资讯系统的 - 已开源
react.js·typescript·github
badhope8 小时前
Matplotlib实战30例:全类型图表代码库
人工智能·python·plotly·github·matplotlib