import { onUnload } from '@dcloudio/uni-app'; /** * 自定义防抖函数钩子 * @param {Function} fn 需要防抖执行的函数 * @param {Number} delay 延迟时间(毫秒) * @returns {Function} 经过防抖处理的函数 */ export function useDebounceFn(fn, delay = 200) { let timer = null; const debounced = (...args) => { // 如果已有定时器,清除它 if (timer) clearTimeout(timer); // 设置新的定时器 timer = setTimeout(() => { fn.apply(this, args); }, delay); }; // 挂载一个 cancel 方法,以便在外部需要时手动清除 debounced.cancel = () => { if (timer) { clearTimeout(timer); timer = null; } }; // 在组件卸载时自动清理定时器,避免内存泄漏 // try-catch 是为了防止在组件外部(非setup环境)使用时报错 try { onUnload(() => { debounced.cancel(); }); } catch (e) { // 如果不是在组件 setup 中调用,忽略 onUnmounted 错误 } return debounced; }