[ uniapp ] 在uniapp中使用防抖函数

/**
 * 防抖函数
 * @param {Function} fn - 需要防抖处理的函数
 * @param {number} delay - 延迟时间(毫秒)
 * @param {boolean} immediate - 是否立即执行
 * @returns {Function} - 返回防抖后的函数
 */

export default function (fn, delay = 300, immediate = false) {
  let timer = null;
  let isExecuted = false;

  return function (...args) {
    const context = this;
    // 清除前一个定时器
    if (timer) clearTimeout(timer);

    // 立即执行的逻辑
    if (immediate && !isExecuted) {
      fn.apply(context, args);
      isExecuted = true;
    }

    // 设置新的定时器
    timer = setTimeout(() => {
      if (!immediate) {
        fn.apply(context, args);
      }
      isExecuted = false;
      timer = null;
    }, delay);
  }
}

uniapp vue2 中使用

import debounce from '@/utils/debounce.js'
export default {
  data() {
    return {};
  },
  methods: {
    // 取消弹窗
    // test() {
    //   console.log('hello world')
    // }

    // 改写为
    // 这里一定要用function, 用箭头函数会导致防抖函数里面的this指向undefined
    test: debounce(function () {
      console.log('hello world')
    })
  },
};

 

posted @ 2025-06-11 09:39  深海里的星星i  阅读(217)  评论(0)    收藏  举报