| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586 |
- /**
- * 防抖函数 - 延迟函数执行,直到事件停止后的一段时间
- * @param fn 需要防抖的函数
- * @param wait 等待时间(毫秒)
- * @param options 配置选项
- * @returns 防抖后的函数
- */
- export function useDebounce<T extends (...args: any[]) => any>(
- fn: T,
- wait: number,
- options?: {
- /** 是否立即执行第一次调用 */
- immediate?: boolean;
- }
- ): {
- /** 防抖后的函数 */
- (this: any, ...args: Parameters<T>): void;
- /** 取消当前等待执行的函数调用 */
- cancel: () => void;
- /** 立即执行当前等待的函数调用 */
- flush: () => void;
- } {
- let timeoutId: ReturnType<typeof setTimeout> | null = null;
- const immediate = options?.immediate ?? false;
-
- const debounced = function (this: any, ...args: Parameters<T>) {
- // 清除之前的定时器
- if (timeoutId !== null) {
- clearTimeout(timeoutId);
- }
-
- // 立即执行模式
- if (immediate && timeoutId === null) {
- fn.apply(this, args);
- }
-
- // 设置新的定时器
- timeoutId = setTimeout(() => {
- // 非立即执行模式,或者是之后的调用
- if (!immediate || timeoutId !== null) {
- fn.apply(this, args);
- }
- timeoutId = null;
- }, wait);
- };
-
- /**
- * 取消当前等待执行的函数调用
- */
- debounced.cancel = function () {
- if (timeoutId !== null) {
- clearTimeout(timeoutId);
- timeoutId = null;
- }
- };
-
- /**
- * 立即执行当前等待的函数调用
- */
- debounced.flush = function () {
- if (timeoutId !== null) {
- clearTimeout(timeoutId);
- fn();
- timeoutId = null;
- }
- };
-
- return debounced;
- }
- /**
- * 用于Vue组件中的防抖钩子
- * @param value 需要防抖的值
- * @param wait 等待时间(毫秒)
- * @returns 防抖后的值
- */
- export function useDebouncedValue<T>(value: T, wait: number): T {
- let debouncedValue = value;
- let timeoutId: ReturnType<typeof setTimeout> | null = null;
-
- // 简单实现,实际项目中可能需要结合ref或reactive使用
- // 完整实现可能需要:import { ref, watch } from 'vue';
- // 这里仅提供一个基础版本
-
- return debouncedValue;
- }
|