当前位置: 首页 > news >正文

防抖与节流

// 防抖函数
function debounce(func, wait, immediate = false) {let timeout;return function executedFunction(...args) {const context = this;const later = function() {timeout = null;if (!immediate) func.apply(context, args);};const callNow = immediate && !timeout;clearTimeout(timeout);timeout = setTimeout(later, wait);if (callNow) func.apply(context, args);};
}// 节流函数
function throttle(func, limit) {let inThrottle;return function(...args) {const context = this;if (!inThrottle) {func.apply(context, args);inThrottle = true;setTimeout(() => inThrottle = false, limit);}};
}// 更精确的节流函数(时间戳版本)
function throttleTimestamp(func, limit) {let lastCall = 0;return function(...args) {const context = this;const now = Date.now();if (now - lastCall >= limit) {lastCall = now;func.apply(context, args);}};
}// 使用示例
// 防抖示例
const debouncedSearch = debounce((query) => {console.log('搜索:', query);
}, 300);// 节流示例
const throttledScroll = throttle(() => {console.log('滚动处理');
}, 100);// 测试
// 快速连续调用
for (let i = 0; i < 10; i++) {setTimeout(() => {debouncedSearch(`查询${i}`);throttledScroll();}, i * 50);
}

核心区别:

防抖(debounce)

  • 在事件触发后等待指定时间,如果在此期间再次触发,则重新计时
  • 适合:搜索框输入、窗口resize

节流(throttle)

  • 在指定时间间隔内只执行一次
  • 适合:滚动事件、鼠标移动

两种方法都能有效控制函数执行频率,根据具体场景选择使用。

http://www.hskmm.com/?act=detail&tid=29717

相关文章:

  • 大数据概述
  • 10月——算法竞赛回坑杂记
  • 20232308 2025-2026-1 《网络与系统攻防技术》实验一实验报告
  • Redis知识点汇总
  • 乐理 -05 乐音 乐级
  • Redis实现分布式锁以及Redis客户端比较
  • 一致性哈希原理
  • 缓存和数据库数据的一致性
  • Redis不同数据类型代码场景实践
  • 布隆过滤器
  • Redis持久化
  • 上下文与this指向
  • [数据库] Microsoft SQL Server 数据库
  • 02 | 在环境中使用Airsim插件
  • 01 | UE5.3+Airsim+VS2022+Windows10(无人机仿真环境)
  • 对于使用ant design组件库的疑问
  • 阅读《构建之法》提出的5个问题
  • 提示工程介绍
  • DshanPI-A1 RK3576 gstreamer播放16路视频与硬件加速
  • freertos的调度过程
  • 「2025 高一上学期笔记 / 日记」
  • 「2025 暑假日记 / 笔记」
  • 2025羊城杯初赛Misc-writeup
  • 将 GPU 级性能带到企业级 Java:CUDA 集成实用指南
  • 我的个人空间
  • 2025.10.12总结
  • Windows 文件管理器中重复的 OneDrive 图标原因与解决方案
  • 10.12总结
  • 【Python】pandas的向量化操作
  • docker部署doris