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.
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.