Event loop

In software, an event loop is an algorithm that continually dispatches control flow for events. The loop requests the next event from an event provider (which generally blocks the loop until an event occurs), and when an event is received, invokes its associated event handler. When the event loop is the central event dispatcher of a program, as it often is, it is called the main loop or main event loop.

In modern environments such as web browsers and server runtimes, the event loop is a fundamental mechanism that enables asynchronous execution by continuously monitoring and dispatching events or messages from a queue when the main program thread is idle. In JavaScript, the event loop allows non-blocking handling of tasks such as user interactions, timers, and I/O operations despite the language being single-threaded

The same algorithm can be used to process inbound messages, a superset of events. In this context, the algorithm is called a message loop, message dispatcher, or message pump. A common use for a message loop is message passing inter-process communication where the message queue is maintained outside of the program (such as by the operating system).

Typically, a program that operates in a graphical user interface (GUI) environment uses an event loop, and due to the predominance of GUI environments, most modern applications have a main event loop.

In the following pseudocode, get_next_message() is a placeholder for a function that is typically provided by the operating system that blocks until a message is available. Thus, the loop only repeats when there is a message to process.

loop
    message := get_next_message()
    process_message(message)
while message != quit