Event Loop
What is Event Loop ?
The event loop is a programming construct or design pattern that waits for and dispatches events or messages in a program.
The event loop almost always operates asynchronously with the message originator.
JavaScript was originally designed to add interactivity to the traditionally static HTML page. To let developers focus on the interactivity logic and need not worry about complex issues in a multi-thread environment such as concurrency and deadlock, JavaScript was designed to be single-threaded
, thus only a single line of JavaScript is being run in that single thread at any given time.
This design caused the program to be synchronous, and with modern websites getting much more complex, the UI might freeze while doing some computationally heavy task, such as waiting for a requested remote resource to response or rendering complex UI.
Event loop is thus introduced to the browser to provide asynchonous ability to handle different tasks.
An important thing to notice is that both browser and Node.js have event loop, but they have different mechanism and implementation details.
Since event loop was introduced to solve interactivity issues within the browser, the specification is actually defined by WHATWG and not included in the ECMAScript specification.
Train of Thoughts
To coordinate events, user interaction, scripts, rendering, networking, and so forth, user agents must use event loops as described in this section. Each agent has an associated event loop, which is unique to that agent.
Deep Dive
Microtask v.s Macrotask
References
- What the heck is the event loop anyway? | Philip Roberts | JSConf EU
- loupe - Event Loop Visualize
- HTML Living Standard - Event Loop
- 事件循环 MICROTASKS (微任务) 的运行时机——从接受知识到探索V8源码
- Event Loop 運行機制解析 - 瀏覽器篇
- Jake Archibald on the web browser event loop, setTimeout, micro tasks, requestAnimationFrame, ...
- Event Loop Fundamentals -- Web Performance Tips
- Tasks, microtasks, queues and schedules