0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Debounce関数を自分で作って理解を深めよう

0
Last updated at Posted at 2026-09-06

フロントエンドの基礎をしっかり勉強していきたいと思い、フロントエンドエンジニア用コーディング試験の例題を解きました。
ほぼほぼ自分用の備忘録ですが、誰かの参考になると幸いです。

Debounceとは?

イベントが連続で発生したときに、そのすべてを連続で発火させないように「イベントを発火させない時間」を作る仕組み。

この記事がわかりやすいです: https://zenn.dev/tyyy/articles/debounce-throttle

実装例

/**
 * @param {(...args: Array<unknown>) => unknown} func
 * @param {number} wait
 * @returns {(...args: Array<unknown>) => void}
 */
export default function debounce(func, wait) {
  let timeoutId = null;
  return function (...args) {
    const context = this; 
    clearTimeout(timeoutId);

    timeoutId = setTimeout(function () {
      timeoutId = null;
      func.apply(context, args);
    }, wait);
  }
}

/**
 * 使用例
 */
const searchBox = {
  inputValue: '',

  handleInput: debounce(function (event) {
    console.log('検索実行:', this.inputValue, event);
  }, 300)
};

// イベントハンドラとして登録
inputElement.addEventListener('input', function (event) {
  searchBox.inputValue = event.target.value;
  searchBox.handleInput(event);
});

学んだこと

  • this
    • 関数が実行されるコンテキストを参照するキーワード、基本function内

    • functionの呼び出され方で参照する値が違う

    • 基本は↓

      image.png
      (引用:https://qiita.com/takkyun/items/c6e2f2cf25327299cf03 )

    • 注:アロー関数は自分自身でthisを持たない

      "use strict";
      
      const obj = {
        i: 10,
        b: () => console.log(this.i, this),
        c() {
          console.log(this.i, this);
        },
      };
      
      obj.b(); // undefined, Window { /* … */ } (またはグローバルオブジェクト) と表示
      obj.c(); // 10, Object { /* … */ } と表示
      

  • setTimeout(func, delay)
    • delayミリ秒待ってからfuncを実行する
    • setTimeoutが返すタイマーIDをclearTimeoutすると、実行前の処理をキャンセルできる

  • 関数.call(thisに設定したい値, 引数1, 引数2, ...)
    • このようにcallを使うことでthisに設定したい値を明示できる
    • .callが本領を発揮するのは、関数がオブジェクトから切り離されて呼ばれる(コールバックとして渡される、変数に代入されるなど)場面で、thisが自動的には正しくならない状況

  • closure
    • 関数自体で複数の呼び出しを超えてこの値を保持しておける仕組み

      export default function debounce(func, wait) {
        let timeoutId = null;        // ← ①ここで変数が生まれる
        return function (...args) {  // ← ②この関数が「その場所」で定義される
          const context = this;
          clearTimeout(timeoutId);   // ← ③ここから①の変数が見える
          timeoutId = setTimeout(function () {
            timeoutId = null;
            func.apply(context, args);
          }, wait);
        }
      }
      
    • この例だと、debounceの呼び出し1回につき1つのtimeoutIdが作られる。同一のdebounceでreturnされた関数は複数の呼び出しを超えて1つのtimeoutIdを参照する。

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?