js防抖、节流函数封装

复制代码
/**
 * 函数节流(Throttle)
 * @param {Function} func 需要节流的函数
 * @param {number} wait 节流间隔(毫秒)
 * @returns {Function}
 */
export function throttle(func, wait = 500) {
  let lastTime = 0;
  let timer = null;
  
  return function(...args) {
    const now = Date.now();
    const remaining = wait - (now - lastTime);

    // 清除延迟执行
    if (timer) {
      clearTimeout(timer);
      timer = null;
    }

    // 到达间隔时间立即执行
    if (remaining <= 0) {
      lastTime = now;
      func.apply(this, args);
    } else {
      // 未到达间隔时间设置延迟执行
      timer = setTimeout(() => {
        lastTime = Date.now();
        timer = null;
        func.apply(this, args);
      }, remaining);
    }
  };
}

/**
 * 函数防抖(Debounce)
 * @param {Function} func 需要防抖的函数
 * @param {number} wait 防抖等待时间(毫秒)
 * @param {boolean} immediate 是否立即执行
 * @returns {Function}
 */
export function debounce(func, wait = 500, immediate = false) {
  let timeout = null;
  
  return function(...args) {
    const context = this;
    
    // 清除已有定时器
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }

    // 立即执行模式
    if (immediate) {
      const callNow = !timeout;
      timeout = setTimeout(() => {
        timeout = null;
      }, wait);
      if (callNow) func.apply(context, args);
    } else {
      // 延迟执行模式
      timeout = setTimeout(() => {
        func.apply(context, args);
        timeout = null;
      }, wait);
    }
  };
}

使用

复制代码
vue3 setup中

// 节流点击处理(每1秒只能触发一次)
    const throttledClick = throttle(() => {
      console.log('Throttled click');
      // 你的业务逻辑
    }, 1000);

    // 防抖输入处理(停止输入500ms后触发)
    const debouncedInput = debounce((value) => {
      console.log('Debounced input:', value);
      // 你的业务逻辑
    }, 500);
相关推荐
yzhSWJ5 分钟前
Spring Boot中自定义404异常处理问题学习笔记
java·javascript
小希爸爸15 分钟前
1、中医基础入门和养生
前端·后端
神仙别闹1 小时前
基于VUE+Node.JS实现(Web)学生组队网站
前端·vue.js·node.js
下雨的Jim1 小时前
前端速成之——Script
前端·笔记
Captaincc2 小时前
使用 Copilot 代理模式构建着陆页
前端·ai编程·github copilot
zyk_5202 小时前
前端渲染pdf文件解决方案-pdf.js
前端·javascript·pdf
Apifox.2 小时前
Apifox 4月更新|Apifox在线文档支持LLMs.txt、评论支持使用@提及成员、支持为团队配置「IP 允许访问名单」
前端·人工智能·后端·ai·ai编程
划水不带桨2 小时前
大数据去重
前端
沉迷...2 小时前
手动实现legend 与 echarts图交互 通过js事件实现图标某项的高亮 显示与隐藏
前端·javascript·echarts
可观测性用观测云3 小时前
观测云数据在Grafana展示的最佳实践
前端