前端防抖实现

在前端开发中,接口防抖(Debouncing)是一种减少频繁触发接口请求的技术,特别适用于用户输入、滚动事件、窗口调整大小等场景。防抖的核心思想是在事件触发后等待一定的延迟时间,如果在这段延迟时间内事件又被重新触发,则重新开始计算延迟时间。只有当指定的时间间隔内没有再次触发事件时,才执行相应的操作。

以下是实现接口防抖的几种方法:

1. 使用lodash库的debounce函数

lodash是一个常用的JavaScript工具库,提供了debounce函数来实现防抖功能。

复制代码
// 引入lodash的debounce函数
import _ from 'lodash';

// 创建一个防抖函数
const debouncedFunction = _.debounce(function() {
  // 这里是你的接口请求逻辑
  console.log('接口请求被触发');
}, 1000); // 1000毫秒的延迟时间

// 使用防抖函数
window.addEventListener('resize', debouncedFunction);

2. 手动实现debounce函数

如果你不想引入额外的库,可以自己实现一个debounce函数:

复制代码
function debounce(func, wait) {
  let timeout;
  return function() {
    const context = this, args = arguments;
    clearTimeout(timeout);
    timeout = setTimeout(() => {
      func.apply(context, args);
    }, wait);
  };
}

// 使用防抖函数
const myDebouncedFunction = debounce(function() {
  console.log('接口请求被触发');
}, 1000);

window.addEventListener('resize', myDebouncedFunction);

3. 使用async/await和Promise实现

复制代码
let timeout = null;

function debounceAsync(func, wait) {
  return async function(...args) {
    const context = this;
    clearTimeout(timeout);
    timeout = setTimeout(async () => {
      await func.apply(context, args);
    }, wait);
  };
}

// 使用防抖函数
const myDebouncedFunctionAsync = debounceAsync(async () => {
  console.log('接口请求被触发');
}, 1000);

window.addEventListener('resize', () => myDebouncedFunctionAsync());

4. 使用requestAnimationFrame实现

对于某些场景,如窗口调整大小或滚动事件,可以使用requestAnimationFrame来实现防抖:

复制代码
let frame = null;

function debounceRAF(func) {
  return function(...args) {
    if (frame !== null) {
      cancelAnimationFrame(frame);
    }
    frame = requestAnimationFrame(() => {
      func.apply(this, args);
    });
  };
}

// 使用防抖函数
const myDebouncedFunctionRAF = debounceRAF(function() {
  console.log('接口请求被触发');
});

window.addEventListener('resize', myDebouncedFunctionRAF);

选择哪种方法取决于你的具体需求和场景。lodashdebounce函数是最简单直接的方法,而手动实现可以给你更多的控制权。对于需要高性能的场景,requestAnimationFrame可能是一个更好的选择。

相关推荐
Ticnix1 小时前
ECharts初始化、销毁、resize 适配组件封装(含完整封装代码)
前端·echarts
纯爱掌门人1 小时前
终焉轮回里,藏着 AI 与人类的答案
前端·人工智能·aigc
twl1 小时前
OpenClaw 深度技术解析
前端
崔庆才丨静觅1 小时前
比官方便宜一半以上!Grok API 申请及使用
前端
星光不问赶路人1 小时前
vue3使用jsx语法详解
前端·vue.js
天蓝色的鱼鱼1 小时前
shadcn/ui,给你一个真正可控的UI组件库
前端
布列瑟农的星空1 小时前
前端都能看懂的Rust入门教程(三)——控制流语句
前端·后端·rust
Mr Xu_1 小时前
Vue 3 中计算属性的最佳实践:提升可读性、可维护性与性能
前端·javascript
jerrywus2 小时前
我写了个 Claude Code Skill,再也不用手动切图传 COS 了
前端·agent·claude
玖月晴空2 小时前
探索关于Spec 和Skills 的一些实战运用-Kiro篇
前端·aigc·代码规范