TS/JS - 什么是防抖和节流函数?有什么区别?

发布时间 2023-11-01 00:43:46作者: Himmelbleu

工具函数

防抖函数和节流函数的区别,可以查看这篇文章,写得比较好:面试官:什么是防抖和节流?有什么区别?如何实现?

防抖(debounce)

通过定时器实现。1 秒内触发了 10 次防抖,定时器是 500ms 执行一次,那么,这防抖函数里面的回调函数只会在 1.5s 之后执行,因为点击的这 10 次,都会清除定时器,导致里面的回调函数没办法执行。

file:[debounce.ts]
export function debounce<T extends (...args: any[]) => void>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timer: number | undefined;

  return function (this: any, ...args: Parameters<T>): void {
    clearTimeout(timer);
    timer = setTimeout(() => {
      func.apply(this, args);
    }, delay);
  };
}

节流(throttle)

节流不管 n 秒内执行多少次,最终都会固定时间触发。如下图所示,很直观:

file:[throttle.ts]

export function throttle<T extends (...args: any[]) => void>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let lastExecTime = 0;

  return function (this: any, ...args: Parameters<T>): void {
    const now = Date.now();
    if (now - lastExecTime >= delay) {
      func.apply(this, args);
      lastExecTime = now;
    }
  };
}