防抖函数TS

60 阅读1分钟
type Timer = ReturnType<typeof setTimeout>;

/**
 * 防抖函数 debounce
 * @param fn
 * @param wait
 * @param opts
 * @returns
 */

export interface DebounceOpts {
  leading: boolean;
  trailing: boolean;
}
export function debounce<F extends (...params: any[]) => void>(fn: F, delay = 500, opts?: DebounceOpts) {
  const options: DebounceOpts = {
    leading: opts?.leading ?? true,
    trailing: opts?.trailing ?? false,
  };

  let timer: Timer | number | null = null;
  return (...args: any[]) => {
    if (!timer && options.leading) {
      fn(...args);
    }

    if (timer) {
      clearTimeout(timer as Timer);
      timer = null;
    }

    timer = setTimeout(() => {
      timer = null;
      options.trailing && fn(...args);
    }, delay || 0);
  };
}

调用

debounce(
    () => {
      
    },
    500,
    {
        leading: true,  // 立即执行第一次点击
        trailing: false, // 忽略后续快速点击
    }
  );