JavaScript イベントループ:ノンブロッキング非同期実行
JavaScript のイベントループは、コールスタックが空のときにキューからコールバックを実行することで非同期操作を管理し、スレッドのブロッキングを防ぎます。
The event loop is a fundamental process in JavaScript's runtime environments (browsers, Node.js) that enables non-blocking asynchronous behavior. Since JavaScript is single-threaded, it can execute only one operation at a time. Without the event loop, long-running tasks (e.g., network requests, timers) would halt the main thread, leading to an unresponsive application. The event loop operates alongside the call stack, browser Web APIs (or Node.js APIs), and a task queue (or callback queue). When an asynchronous task is initiated, it's delegated to the appropriate API. Upon completion, its associated callback function is placed in the task queue. The event loop continuously checks if the call stack is clear. If it is, it dequeues the oldest callback from the task queue and pushes it onto the call stack for execution. This cycle ensures that asynchronous operations are handled efficiently without blocking the primary thread.
graph LR
Center["JavaScript イベントループ:ノンブロッキング非同期実行"]:::main
classDef main fill:#7c3aed,stroke:#8b5cf6,stroke-width:2px,color:white,font-weight:bold,rx:5,ry:5;
classDef pre fill:#0f172a,stroke:#3b82f6,color:#94a3b8,rx:5,ry:5;
classDef child fill:#0f172a,stroke:#10b981,color:#94a3b8,rx:5,ry:5;
classDef related fill:#0f172a,stroke:#8b5cf6,stroke-dasharray: 5 5,color:#94a3b8,rx:5,ry:5;
linkStyle default stroke:#4b5563,stroke-width:2px;
🧒 5歳でもわかるように説明
[JavaScript](/ja/terms/javascript) を、一度に 1 つのことしかできないシェフだと考えてください。もし彼がケーキを焼く必要がある(長いタスク)場合、ただ立って待っているだけではありません。彼はケーキをオーブンに入れ、タイマーをセットし、すぐにサラダ(別のタスク)の準備を始めます。オーブンのタイマーが鳴ったら、シェフはサラダを終え、ケーキを取り出し、それから他のことをします。イベントループは、シェフがこれらの「待機」タスクを管理するシステムのようなもので、他の作業を止めずに、準備ができたときに処理されることを保証します。
🤓 Expert Deep Dive
JavaScript のイベントループは、コード、タスク、イベントの実行をオーケストレーションする並行処理モデルです。コールスタックとタスクキューを継続的に監視します。同期コードはコールスタック上で直接実行されます。非同期操作(例:setTimeout、Promises、I/O)は、ホスト環境の API に委譲され、その実行が管理されます。非同期操作が完了すると、そのコールバック(または Promise の解決ハンドラ)は、対応するキューに入れられます。タスクキュー(setTimeout、DOM イベントなどのマクロタスク用)またはマイクロタスクキュー(Promises、queueMicrotask などのマイクロタスク用)です。イベントループの主な機能は、コールスタックが空になったときに、タスクをキューから取り出して実行することです。マイクロタスクは通常、マクロタスクの前に処理されます。具体的には、現在のマクロタスクが終了した後、次のマクロタスクが開始される前に、イベントループは利用可能なすべてのマイクロタスクを実行します。これにより、遅延されたコールバックよりも即時のコールバック(Promise の解決など)が優先され、さまざまな JavaScript 環境での応答性と非同期操作の効率的な処理が保証されます。