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](/ko/terms/javascript)를 한 번에 한 가지 일만 할 수 있는 요리사라고 생각해보세요. 케이크를 구워야 하는 긴 작업이 있다면, 그냥 서서 기다리지 않습니다. 오븐에 케이크를 넣고 타이머를 설정한 다음, 즉시 샐러드를 준비하기 시작합니다(다른 작업). 오븐 타이머가 울리면 요리사는 샐러드를 마친 후 케이크를 꺼내고 다른 일을 합니다. 이벤트 루프는 요리사가 이러한 '대기' 작업을 관리하는 시스템과 같아서, 다른 작업을 중단하지 않고 준비가 되었을 때 처리되도록 합니다.

🤓 Expert Deep Dive

JavaScript 이벤트 루프는 코드, 작업 및 이벤트의 실행을 조정하는 동시성 모델입니다. 콜 스택과 작업 큐를 지속적으로 모니터링합니다. 동기 코드는 콜 스택에서 직접 실행됩니다. 비동기 작업(예: setTimeout, Promises, I/O)은 실행을 관리하는 호스트 환경의 API로 위임됩니다. 비동기 작업이 완료되면 해당 콜백(또는 Promise의 이행 핸들러)이 해당 큐, 즉 작업 큐(setTimeout, DOM 이벤트와 같은 매크로 작업용) 또는 마이크로태스크 큐(Promises, queueMicrotask와 같은 마이크로 작업용)에 배치됩니다. 이벤트 루프의 핵심 기능은 콜 스택이 비어 있을 때 큐에서 작업을 꺼내 실행하는 것입니다. 마이크로태스크는 일반적으로 매크로태스크보다 먼저 처리됩니다. 구체적으로, 현재 매크로태스크가 완료된 후 다음 매크로태스크가 시작되기 전에 이벤트 루프는 사용 가능한 모든 마이크로태스크를 실행합니다. 이는 지연된 콜백보다 즉각적인 콜백(Promise 해결 등)을 우선시하여 다양한 JavaScript 환경에서 응답성과 비동기 작업의 효율적인 처리를 보장합니다.

📚 출처