useDebounceFn.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import { onUnload } from '@dcloudio/uni-app';
  2. /**
  3. * 自定义防抖函数钩子
  4. * @param {Function} fn 需要防抖执行的函数
  5. * @param {Number} delay 延迟时间(毫秒)
  6. * @returns {Function} 经过防抖处理的函数
  7. */
  8. export function useDebounceFn(fn, delay = 200) {
  9. let timer = null;
  10. const debounced = (...args) => {
  11. // 如果已有定时器,清除它
  12. if (timer) clearTimeout(timer);
  13. // 设置新的定时器
  14. timer = setTimeout(() => {
  15. fn.apply(this, args);
  16. }, delay);
  17. };
  18. // 挂载一个 cancel 方法,以便在外部需要时手动清除
  19. debounced.cancel = () => {
  20. if (timer) {
  21. clearTimeout(timer);
  22. timer = null;
  23. }
  24. };
  25. // 在组件卸载时自动清理定时器,避免内存泄漏
  26. // try-catch 是为了防止在组件外部(非setup环境)使用时报错
  27. try {
  28. onUnload(() => {
  29. debounced.cancel();
  30. });
  31. } catch (e) {
  32. // 如果不是在组件 setup 中调用,忽略 onUnmounted 错误
  33. }
  34. return debounced;
  35. }