Skip to content

debounce() function

debounce 関数は、デバウンスされた関数が最後に呼び出されてから指定された時間が経過するまで、提供された関数の実行を遅延させるために使用されます。この関数は、特にユーザー入力イベント、スクロール、リサイズなどのシナリオで、関数が実行される速度を制限することによってパフォーマンスを最適化するのに役立ちます。さらに、debounce 関数は、最初の呼び出しで即座に関数を実行することができ(leading が true に設定されている場合)、.cancel() メソッドを使用して手動でキャンセルできます。

Signature:

typescript
declare function debounce<T extends (...args: any[]) => void>(
  func: T,
  wait: number,
  options?: {
    leading: boolean;
  },
): ((...args: Parameters<T>) => void) & {
  cancel: () => void;
};

Example

ts
const debounced1 = debounce((val: number) => {
  console.log("val", val);
}, 100);

debounced1();
debounced1();
debounced1(); // invoke func after 100ms

const debounced2 = debounce(
  (val: number) => {
    console.log("val", val);
  },
  100,
  { leading: true },
);
debounced2(); // immediately invoked func
debounced2();
debounced2(); // invoked func after 100ms

const debounced3 = debounce((val: number) => {
  console.log("val", val);
}, 100);
debounced3();
debounced3();
debounced3.cancel(); // cancel func

Open Source Code

Released under the Apache-2.0 License.