| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869 |
- /**
- * 防抖函数 - 延迟函数执行,直到事件停止后的一段时间
- * @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;
- }
|