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);
相关推荐
Wyc7240944 分钟前
HTML:入门
前端·html
Sunny_lxm1 小时前
自定义列甘特图,原生开发dhtmlxgantt根特图,根据数据生成只读根特图,页面展示html demo
前端·html·甘特图·dhtmlxgantt
熊猫钓鱼>_>2 小时前
建筑IT数字化突围:建筑设计企业的生存法则重塑
前端·javascript·easyui
GISer_Jing4 小时前
前端性能指标及优化策略——从加载、渲染和交互阶段分别解读详解并以Webpack+Vue项目为例进行解读
前端·javascript·vue
不知几秋4 小时前
数字取证-内存取证(volatility)
java·linux·前端
水银嘻嘻5 小时前
08 web 自动化之 PO 设计模式详解
前端·自动化
Zero1017137 小时前
【详解pnpm、npm、yarn区别】
前端·react.js·前端框架
&白帝&7 小时前
vue右键显示菜单
前端·javascript·vue.js
Wannaer7 小时前
从 Vue3 回望 Vue2:事件总线的前世今生
前端·javascript·vue.js
羽球知道8 小时前
在Spark搭建YARN
前端·javascript·ajax