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);
相关推荐
前端一小卒3 分钟前
AI 时代,前端工程化要重做一遍
前端
橙子家9 小时前
浏览器缓存之【基础键值存储】:Local storage 和 Session storage
前端
星星在线11 小时前
MusicFree:一个「All in One」的个人音乐服务器,让听歌回归简单
前端·后端
IT_陈寒12 小时前
Redis的SETNX并发问题让我加了三天班
前端·人工智能·后端
demo007x12 小时前
Docling 文档转换以及技术架构分析
前端·后端·程序员
京东云开发者13 小时前
京东市民服务又“上新”!这次是黑龙江“龙易办”
前端
袋鱼不重14 小时前
我的神奇同事,AI 用多了居然写了个 Open In Codex
前端·后端·ai编程
竹林81814 小时前
Web3表单签名验证:我用 wagmi 和 ethers 给 DApp 加了一个“免密登录”,踩坑记录全在这了
javascript
用户69903048487514 小时前
try catch使用场景 处理同步代码错误兼容用的
javascript·uni-app
雪碧聊技术14 小时前
Tree.js是什么?一文讲透
开发语言·javascript·ecmascript