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);
相关推荐
雪芽蓝域zzs6 小时前
第 5 节:Marker 点击弹出 InfoWindow 信息窗口
vue.js
回眸&啤酒鸭6 小时前
【回眸】OpenSwarm 多智能体协作系统实战指南
大数据·前端·人工智能
用户69371750013847 小时前
2026,程序员的时代拐点到了
android·前端·后端
大龄秃头程序员7 小时前
一次 iBeacon + BLE 无感解锁方案的实现记录
前端
小兔子7 小时前
Python 的 GIL 与 free-threading:3.13 之后「去 GIL」走到哪一步了
前端
IT_陈寒7 小时前
SpringBoot自动配置差点让我加班到凌晨
前端·人工智能·后端
guslegend8 小时前
脚手架原理与本地调试:从 bin 软链接到 npm link
前端·npm·node.js·脚手架·前端工程化
小宋10218 小时前
A2UI从零实战:Agent安全生成交互界面与事件回传
javascript·人工智能·安全·交互
大包子9 小时前
structuredClone vs lodash.cloneDeep:核心差异与选型指南
javascript·vue.js
海码事务所9 小时前
Google Play 新个人开发者账号上架指南:12 人连续 14 天封闭测试怎么做?
前端