0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

🎯JavaScriptで完全マスター!`Debounce`と`Throttle`の違いと使い所【リアルタイム例付き】

Posted at

こんにちは!アミットです。
今回は、JavaScriptのフロントエンド開発で頻出の「Debounce(デバウンス)」と「Throttle(スロットル)」について、初心者にもわかりやすく、リアルな例で解説していきます!


🔍 Debounce(デバウンス)とは?

一定時間イベントが発生し続けなかった場合にだけ、最後の処理を実行するテクニック。

📦 使いどころ

  • 検索ボックスの入力補完APIの呼び出し
  • ウィンドウサイズの変更後のレイアウト再計算
  • スクロール終了後の処理

🧪 リアルタイム例:検索ボックスのAPI呼び出し

function debounce(func, delay) {
  let timer;
  return function (...args) {
    clearTimeout(timer);
    timer = setTimeout(() => func.apply(this, args), delay);
  };
}

const fetchSearchResults = (query) => {
  console.log(`🔍 Searching for: ${query}`);
};

const debouncedSearch = debounce(fetchSearchResults, 500);

document.getElementById("searchBox").addEventListener("input", (e) => {
  debouncedSearch(e.target.value);
});
<input type="text" id="searchBox" placeholder="キーワードを入力..." />

✅ ユーザーが入力を止めて500ms経ったら、fetchSearchResultsが呼ばれます。


⚡ Throttle(スロットル)とは?

一定間隔でしか関数を実行しないように制御するテクニック。

📦 使いどころ

  • スクロールイベントに連動した画像の遅延読み込み
  • マウス移動の追跡(例:カスタムカーソル)
  • リサイズ処理の制限

🧪 リアルタイム例:スクロール時のヘッダー表示制御

function throttle(func, interval) {
  let lastTime = 0;
  return function (...args) {
    const now = Date.now();
    if (now - lastTime >= interval) {
      func.apply(this, args);
      lastTime = now;
    }
  };
}

const onScroll = () => {
  console.log("📜 スクロール中...");
};

window.addEventListener("scroll", throttle(onScroll, 300));

✅ スクロールイベントが多発しても、300msに1回しかonScrollが呼ばれません!


🤔 Debounce と Throttle の違いまとめ

特徴 Debounce Throttle
実行タイミング イベント終了後 定期的に実行
使用例 入力、検索 スクロール、マウス移動
API呼び出し頻度 少ない(最後のみ) 一定間隔で発生

🧠 覚え方のコツ

Debounce(でばうんす):入力が止まったら発火(=ユーザーの「考え中」に優しい)
Throttle(すろっとる):大量イベントを間引く(=パフォーマンス改善に最適)


🛠 よく使われるライブラリ

  • Lodash
import _ from 'lodash';

_.debounce(myFunc, 300);
_.throttle(myFunc, 300);
  • RxJS(リアクティブプログラミング向け)

🎁 おまけ:使い分けチャート

入力系イベント → Debounce
ユーザーの動き追跡 → Throttle

✍️ まとめ

  • debounceは「入力を止めた後に発火」する
  • throttleは「一定間隔で発火」する
  • パフォーマンスとユーザー体験の両立には欠かせないテクニック

最後まで読んでいただきありがとうございます!
💬 質問・感想はコメントでお気軽に!
👨‍💻 他にもReact・Vue・AIなど技術記事を投稿してますので、ぜひフォローしてくださいね!


📌 Qiitaタグ案:

JavaScript フロントエンド パフォーマンス最適化 Throttle Debounce 初心者向け

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?