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

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);


http://www.kler.cn/a/580889.html

相关文章:

  • Python已知后序遍历和中序遍历,求先序遍历
  • 探索AIGC中的自动化生成
  • Python Flask 在网页应用程序中处理错误和异常
  • python实现的生态模拟系统
  • 牛客周赛:84:C:JAVA
  • P9242 [蓝桥杯 2023 省 B] 接龙数列--DP【巧妙解决接龙问题】
  • AI 帮我精准定位解决 ReferenceError: process is not defined (文末附AI名称)
  • Spring WebFlux:响应式编程
  • python使用venv命令创建虚拟环境(ubuntu22)
  • OSPF:虚链路
  • 零基础掌握Linux SCP命令:5分钟实现高效文件传输,小白必看!
  • Unity Dots从入门到精通 Mono和Dots通讯
  • DOCKER模式部署GITLAB
  • 回溯-子集
  • Java集合_八股场景题
  • vue2动态增删表单+表单验证
  • WPF预览并打印FlowDocument
  • Python数据分析之数据处理与分析
  • 修改 Docker 网桥的 IP 范围
  • Oracle RAC配置原理详解:构建高可用与高性能的数据库集群