What is Event loop?

The mechanism by which a JavaScript runtime takes waiting work one item at a time and runs it on a single thread. Work triggered by clicks, timers, completed network requests and so on is queued as tasks, and when the current code finishes, the event loop takes the next task. Promise callbacks (microtasks) all run after each task finishes, before the next task. If one piece of work runs for a long time, handling of other events and painting of the screen stop.

Japanese name: イベントループ

Event loop appears in 1 practice question across 1 topic, including Web Technology Basics.

Field: Web Technology Basics

Order of execution

For example, if console.log('A') is followed by scheduling the output of B with setTimeout and of C with a Promise's then, and finally console.log('D') runs, the output order is A, D, C, B. All the synchronous code runs first, then the microtask C, and finally the task B. Even with a delay of 0 ms, setTimeout does not run immediately.

Why the screen freezes

The browser's main thread handles running JavaScript, processing events such as clicks and painting the screen. If a calculation that takes several seconds runs in one go, the event loop cannot take the next task during that time, so buttons do not respond and the screen is not updated. Heavy calculations are moved to another thread with a Web Worker, or split into small pieces and run a little at a time.

Asynchronous I/O

For network requests and file reads and writes, the thread is not blocked while waiting for completion; instead, the code to call when it finishes (a callback or a Promise) is registered. On completion that code is queued as a task, and the event loop runs it in turn. Server-side runtimes such as Node.js use the same idea, running JavaScript on a single thread while handling many connections.

FAQ

Does setTimeout with 0 ms run immediately?

No. After the specified time it is queued as a task, and it runs only after the currently running code and any microtasks queued so far have finished. 0 ms means "as soon as possible, but after the current work".

Can JavaScript compute in parallel?

The page's JavaScript itself runs on a single main thread, but a Web Worker can run a script in parallel on another thread. Workers cannot touch the DOM directly, so they exchange messages with the main thread to pass results.

Event loop in the explanations

Questions that mention Event loop (1)

  1. When the JavaScript above is run in a browser, which of the following is the order in which the characters are shown on the console?

Books on Web Technology Basics Ad

As an Amazon Associate I earn from qualifying purchases.

Related terms

Queue Cookie (HTTP cookie) CORS (cross-origin resource sharing) DOM (Document Object Model) HTTP (Hypertext Transfer Protocol) HTTP method HTTP status code JSON (JavaScript Object Notation) JWT (JSON Web Token) OAuth

Back to the glossary