An event loop is a control structure that repeatedly waits for, selects, and dispatches events or executable work. Events may represent user input, network activity, timer expiration, messages from other components, or the completion of an asynchronous operation. Instead of following only a predetermined sequence of instructions, an event-driven program registers actions to perform when particular conditions arise. The loop connects those conditions to the code that handles them.
Event loops underpin graphical applications, network servers, and many systems for asynchronous programming. They allow a program to coordinate numerous activities without dedicating a continuously executing thread to every activity. Their importance is especially visible in web browsers, where user interaction, scripts, networking, and rendering must be coordinated, and in server runtimes that manage large numbers of network connections.
An event loop is not a universal scheduling algorithm or a guarantee of parallel execution. Implementations differ in their event sources, queue organization, priority rules, timer behavior, and relationship to operating-system facilities. Understanding an event loop therefore requires distinguishing its general dispatch mechanism from the specific rules supplied by a graphical toolkit, language runtime, or platform specification.
Core mechanism and execution model
The central operation of an event loop is dispatch: selecting an eligible unit of work and invoking the code associated with it. A typical implementation maintains registered event sources, runnable work, and scheduled timers. When no work can proceed immediately, it waits until an external event occurs or a deadline becomes due. When work becomes available, it invokes a handler and then returns to scheduling. The handlers may register new operations, remove existing registrations, or make additional handlers runnable.
A simplified loop can be expressed in pseudocode:
while not stopping:
timeout = time_until_next_deadline()
events = wait_for_events(timeout)
update_ready_work(events)
make_due_timers_runnable()
dispatch_selected_work()
This describes a family of implementations rather than a required order of operations. Some loops examine timers before polling; others maintain distinct phases for different event classes. Some dispatch one handler per iteration, while others execute a batch. A production implementation also handles cancellation, exceptions, shutdown, wake-up signals, and changes to registered resources.
A handler is often a callback function: code supplied to a framework for invocation when an event occurs. An application might register one callback for a button press and another for incoming data on a connection. Event-driven code can also be expressed through objects, messages, or resumable tasks rather than explicit callback functions. The loop schedules executable work regardless of how the application presents it syntactically.
Many event loops execute application handlers on a single thread. Within that thread, a handler ordinarily runs until it returns, throws an exception, or explicitly suspends through the runtime’s asynchronous machinery. This is commonly described as run-to-completion execution. It does not mean the operating system cannot preempt the thread, nor that no other thread can execute simultaneously. It means the loop does not normally interrupt one handler merely to dispatch another handler on the same thread.
The loop must also be able to sleep efficiently. Repeatedly checking every event source without waiting is busy polling and can consume a processor even when no useful work exists. General-purpose loops normally use a blocking operating-system wait, together with a wake-up mechanism for newly submitted work. Specialized low-latency systems sometimes deliberately poll, exchanging greater processor use for reduced waiting overhead. Whether blocking or polling is appropriate depends on the workload, latency requirements, and deployment environment.
Operating-system interfaces and I/O notification
Event loops depend heavily on the facilities provided by an operating system. For network services, the central requirement is often to observe many communication endpoints without blocking separately on each one. I/O multiplexing provides interfaces through which one wait operation can monitor multiple descriptors or handles. Traditional Unix interfaces include select and poll; later facilities include epoll on Linux and kqueue on several BSD-derived systems.
An important distinction is between readiness notification and completion notification. Readiness indicates that an operation may be attempted without blocking under the interface’s rules. A readable network socket may contain data, report an orderly closure, or expose an error. The application still performs an operation to discover the result. Completion notification instead reports that a previously submitted operation has finished, normally with a result such as a byte count or error code. Windows I/O completion ports are a major example of completion-oriented infrastructure.
A readiness-based loop is commonly associated with the reactor pattern. It waits for notifications and dispatches handlers that perform the actual I/O. Completion-based designs are often associated with the proactor pattern, in which operations are initiated in advance and handlers process their results. Actual libraries may combine these approaches. Linux io_uring, introduced in Linux 5.1 in 2019, provides submission and completion queues for supported operations and can be used within a broader event-loop implementation.
Readiness interfaces also differ in their notification semantics. With level-triggered notification, a source generally remains reportable while the relevant condition holds. With edge-triggered notification, notification corresponds to a change in readiness state. For edge-triggered socket handling, a common discipline is to continue reading or writing until a nonblocking operation reports that it would block. Stopping prematurely can leave data unprocessed without a new transition to trigger another notification. Readiness can also become stale before a handler acts, particularly when resources are shared, so robust code still handles nonblocking failure results.
Not every slow operation fits a socket-readiness model. Regular-file access, hostname resolution, and certain platform services may block or lack a suitable asynchronous interface. Libraries therefore often combine native I/O notification with a worker pool. A worker performs the blocking operation, then signals the loop so its result can be delivered in the usual execution context. Consequently, an application described as “single-threaded” at the handler level may still rely on multiple supporting threads inside its runtime.
Queues, timers, ordering, and fairness
The phrase “the event queue” is a useful simplification, but many implementations maintain several queues or scheduling structures. Ready callbacks may occupy a first-in, first-out queue, timers may be organized by deadline, and user-interface work may have its own priority classes. The choice of data structure affects both performance and semantics. A minimum heap supports efficient retrieval of the earliest timer, while timing wheels group deadlines into time intervals and are useful in some high-volume timer systems.
A timer usually establishes an eligibility time, not an exact execution time. If a timer becomes due while another handler is executing, its callback must wait until the loop can dispatch it. A requested delay of 10 milliseconds therefore does not promise execution precisely 10 milliseconds later. The observed delay also reflects operating-system scheduling, clock granularity, suspended processes, queue backlog, and runtime policies such as browser timer throttling. Relative timeouts are commonly measured using a monotonic clock so that changes to civil time do not unexpectedly alter elapsed-time calculations.
Ordering guarantees are local to a particular interface. A queue may preserve insertion order while the overall loop does not provide one global first-in, first-out ordering across input, network activity, timers, and internal jobs. Events detected in the same polling operation can be dispatched according to implementation-specific rules. An asynchronous operation’s completion time is also distinct from the time its continuation executes. The completion may first need to be observed, translated into a runnable item, and selected by the scheduler.
Fairness concerns whether one source can indefinitely postpone another. A loop that drains a queue until it is empty can be monopolized if every dispatched item adds more items to that queue. One mitigation is to process only the items present at the start of a scheduling round; another is to impose a batch limit or time budget. Priority-based loops face a related risk: a constant stream of high-priority events may starve lower-priority work. These choices trade throughput, responsiveness, and scheduling overhead rather than admitting one universally optimal policy.
Loops also need explicit rules for work submitted from other threads. A thread-safe submission interface generally combines a protected or concurrent queue with a wake-up signal. The signal causes the polling thread to notice new work even if it was waiting indefinitely. Correctness depends on coordinating the queue and wake-up state so that no submission becomes invisible during the transition into sleep. This is a form of synchronization, even when the application callbacks themselves execute sequentially.
Browser event loops and JavaScript execution
The browser event loop coordinates script execution with input processing, networking, and rendering. The HTML Standard defines event-loop behavior for web-platform environments, while the JavaScript language specification defines language-level execution machinery and jobs. These are related but distinct layers. JavaScript is not intrinsically limited to a browser event loop, and browser scheduling cannot be derived solely from the language’s syntax.
Browser specifications distinguish tasks from microtasks. Tasks include work associated with timer callbacks, event dispatch, and other platform activities. An event loop can have multiple task queues, with task sources providing ordering constraints for related work. A microtask checkpoint drains the microtask queue, including microtasks added while that checkpoint is running. Promise reactions and callbacks scheduled with queueMicrotask use this machinery. Checkpoints occur at specified points, including after task processing and at certain boundaries when script execution unwinds.
The distinction can be illustrated by an ordinary browser script:
console.log("A");
setTimeout(() => console.log("D"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("B");
Under the usual execution conditions, the output is A, B, C, D. The synchronous statements run first. The promise reaction is executed through microtask processing, while the timer callback requires a later task. A zero timeout does not interrupt the current script. This example establishes a particular ordering relationship; it does not imply that all unrelated browser tasks share one universal queue.
Rendering is another scheduling responsibility. At rendering opportunities, the browser can perform work that includes animation callbacks, style and layout calculations, and presentation-related updates. requestAnimationFrame schedules a callback for an animation-frame opportunity rather than promising an exact interval. A 60-hertz display has a nominal refresh interval of about 16.7 milliseconds, but that is not a guaranteed budget for script alone. Other work also consumes time, and background pages or constrained devices may receive fewer rendering opportunities. Changes to the Document Object Model are not necessarily painted immediately after the statement that makes them.
Long-running scripts prevent the same event loop from responding promptly to other work. A self-perpetuating chain of microtasks can likewise delay tasks and rendering even though each individual callback is short. Web workers provide separate execution environments that can process work independently and communicate through messages; they do not make ordinary page code parallel automatically. Browser responsiveness therefore depends both on the duration of individual handlers and on the scheduler’s ability to advance between categories of work.
Server and language-runtime implementations
Server runtimes adapt event loops to connection management, protocol processing, and asynchronous application code. Node.js, created by Ryan Dahl and first released in 2009, made server-side JavaScript closely associated with this model. Its architecture combines a JavaScript execution environment with native platform services. The fact that many callbacks run on one event-loop thread does not mean that network I/O, runtime internals, or all application computation occur on only one thread.
A major component of Node.js is libuv, a cross-platform library that supplies event-loop and asynchronous I/O facilities. Its loop includes phases associated with timers, pending callbacks, polling, check callbacks, and close callbacks, along with internal preparation stages. The poll phase is central to collecting I/O events and dispatching associated callbacks. setImmediate callbacks run in the check phase. File-system operations and some other services use libuv’s worker pool rather than behaving like readiness-driven network sockets.
Phase details are version-dependent. Beginning with libuv 1.45.0, adopted in Node.js 20, timer processing changed to run after polling rather than both before and after polling. Such changes can affect interactions between timers and immediate callbacks. Node.js also provides process.nextTick, whose queue is distinct from the ordinary phase queues, and integrates promise microtasks. Their relative ordering depends on execution context, including differences between ordinary CommonJS execution and ECMAScript module evaluation. Simplified diagrams are therefore useful guides but not complete specifications for every observable ordering.
In Python, asyncio supplies an event loop together with futures, tasks, transports, and higher-level facilities for asynchronous networking and subprocesses. It entered the standard library in Python 3.4 in 2014. A task drives a coroutine, resuming it when an awaited operation permits progress. A coroutine that performs ordinary computation without reaching an effective suspension point can block other tasks on that loop, just as a long callback can. The presence of await in a function does not by itself guarantee frequent or fair suspension.
Other ecosystems expose similar machinery through different abstractions. Qt integrates input, timers, object notifications, and asynchronous operations through event loops. Java NIO offers selectors that applications and frameworks can use to build readiness-driven services. Rust asynchronous runtimes poll futures through executors, often using an I/O driver integrated with the runtime. Some runtimes use a single execution thread; others use multiple worker threads and work-stealing schedulers. The term “event loop” may refer to the central dispatcher, an I/O-driving component, or a broader runtime architecture, so comparisons require identifying the exact component under discussion.
Callbacks, coroutines, and concurrency
An event loop supplies scheduling infrastructure, while asynchronous programming abstractions determine how application code expresses suspended work. With callbacks, the program explicitly states what should happen after an operation finishes. A network client might initiate a connection, register a callback for connection success, then register another callback for received data. Dependencies are represented by registrations and captured state rather than by a single uninterrupted sequence of calls.
This structure is related to a finite-state machine. A connection may move through states such as connecting, negotiating, reading a request, writing a response, and closing. Each event changes the state and determines which operations are valid next. Explicit state machines can make protocol behavior precise, but callback-based code becomes difficult to follow when success paths, failures, cancellation, and resource cleanup are scattered among many handlers. The problem is organizational rather than a necessary flaw in event-driven execution.
A promise represents an eventual result or failure and provides a way to attach dependent computation. Futures serve related roles, although the terminology and capabilities vary between languages. A coroutine can make this dependency structure resemble sequential code: it begins an operation, suspends while waiting, and resumes with a result. The runtime preserves the coroutine’s state across suspension. This changes the expression of control flow without requiring one operating-system thread per suspended operation.
An await expression does not necessarily yield control. If the awaited object is already ready, some runtimes can continue immediately. Conversely, suspension creates a point at which other tasks may modify shared application state. A handler that reads an account balance, awaits a service call, and later writes an updated balance can conflict logically with another task performing the same sequence. Single-threaded execution removes simultaneous instruction execution on that thread, but it does not eliminate all race conditions involving interleaved operations.
This distinction separates concurrency from parallelism. Concurrency allows multiple activities to remain in progress; parallelism executes work simultaneously on multiple processing resources. An event loop can coordinate thousands of outstanding operations while executing only one application callback at a time. CPU-intensive work may instead be divided into short cooperative steps or transferred to worker threads or processes. Cancellation adds another layer: canceling a waiting task may stop its continuation without undoing an operation already performed externally. Resource ownership, failure propagation, and cancellation semantics must therefore be defined above the loop’s basic dispatch mechanism.
Performance, overload, and backpressure
Event loops are particularly effective when many operations spend much of their lifetime waiting for external activity. A network server may have thousands of open connections while only a small fraction are ready to exchange data at any moment. Maintaining suspended state for each connection can use less memory than allocating a separate operating-system thread stack for each one. However, this is a workload-dependent advantage, not evidence that event loops are always faster than threaded designs.
A single loop thread has a finite execution budget. If handlers arrive at average rate , and their average exclusive processing time on that thread is , a simplified utilization estimate is
Sustained operation requires spare capacity; as utilization approaches full occupancy, queueing delays can increase substantially. This estimate excludes many implementation costs and does not fully characterize bursty workloads, but it identifies the core constraint: waiting on external I/O can overlap, whereas application instructions executed on one loop thread still compete for the same processor time.
Long handlers are especially damaging to latency. A 200-millisecond synchronous computation can delay unrelated timers, connection handling, and user-interface activity on that loop. Even when average handler time is small, occasional large tasks can dominate tail latency. Measuring event-loop lag, typically by comparing a scheduled callback’s intended and actual execution times, helps expose scheduling delays. It does not by itself identify their cause: processor contention, garbage collection, synchronous I/O, and large callback batches can produce similar symptoms.
Backpressure controls the mismatch between a producer’s rate and a consumer’s capacity. If a service reads incoming data faster than it can process or transmit the results, queues grow. An asynchronous write call may merely copy data into a user-space buffer; it does not necessarily mean that the peer has received anything. Stream interfaces commonly expose high-water marks, writable-state notifications, or awaitable drain operations. These mechanisms let upstream stages slow down instead of treating unlimited buffering as unlimited capacity.
A useful relation from queueing theory is Little’s law:
where is the average number of items in a system, is its long-run arrival rate, and is average time spent in that system, under the law’s stability assumptions. If response time rises while the admitted arrival rate remains high, the number of outstanding requests and associated memory can grow. Practical architectures therefore combine event loops with bounded queues, admission control, connection limits, and load balancing. An event loop reduces some coordination costs; it does not supply an overload policy automatically.
Historical development and correctness boundaries
Event loops emerged from several lines of interactive and systems programming rather than from one invention. Early interactive systems needed to respond to inputs that arrived independently of a program’s sequential calculations. Graphical window systems later made repeated event retrieval and dispatch a standard application structure. The classic Macintosh application model, introduced with the Macintosh in 1984, placed responsibility for retrieving and handling events in the application. Microsoft Windows established another influential message-loop model, in which applications retrieve queued messages and dispatch them to window procedures.
Unix network programming developed a complementary tradition around multiplexed descriptors. Servers could use readiness notification to handle many connections without assigning a blocking execution path to each. The X Window System, first developed in 1984, combined network communication with event-oriented graphical interaction. In the 1990s, architecture literature gave widely used names to reactor and proactor patterns. During the 2000s and 2010s, browser programming, Node.js, and coroutine-based libraries brought event-loop concepts into mainstream application development.
A key correctness boundary is reentrancy. Although ordinary handlers may run to completion, a handler can sometimes call an operation that starts a nested event loop. Modal dialogs and synchronous-looking framework APIs have historically done this in some graphical environments. While the outer handler is suspended, the nested loop may dispatch other callbacks that inspect or modify the same objects. Assumptions such as “this state cannot change until the handler returns” then become invalid. Reentrancy can also occur through direct synchronous callbacks, without a second loop.
Lifecycle management introduces additional hazards. A queued callback may refer to an object that has been logically closed, and a notification may arrive after cancellation has begun. Removing a resource from a polling mechanism does not universally guarantee that every previously observed notification has disappeared. Frameworks address these problems through ownership rules, generation identifiers, reference management, and explicit state checks. Exception handling likewise requires a defined boundary: an exception may reject a task, invoke a framework error handler, or escape and terminate the loop, depending on the runtime and API.
Testing must account for both ordering and time. A test that assumes a timer fires at an exact instant is fragile under load. Virtual clocks and controlled schedulers can make timeout behavior reproducible, but they must model the relevant distinction between advancing time and dispatching runnable work. Formal verification can express properties such as eventual service of an enabled task or the impossibility of using a resource after closure. Such properties depend on explicit assumptions about scheduler fairness, cancellation, external events, and handler termination; they do not follow merely from adopting an event-driven architecture.