Skip to main content

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.

-- WIKIPEDIA - Event Loop

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.

Fun fact

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.

-- WHATWG HTML Living Standard - Event Loop

Deep Dive

Microtask v.s Macrotask

References