JavaScript executes programs in an event-driven manner, providing developers with a single thread (the main thread) that executes tasks sequentially, one at a time. To reduce the load on the main thread, I/O operations such as network requests are handled by a separate thread pool. Additionally, JavaScript supports the execution of web workers for long-running tasks that can be processed independently of the main thread. This allows developers to utilize parallel processing without directly dealing with multi-threaded programming.
Each thread running in the JavaScript engine (the main thread and each web worker) has its own event loop and task queue. In the case of web workers, the task queue is sometimes referred to as a message queue, but they are fundamentally the same concept. (Strictly speaking, web workers have separate message queues, and the main thread processes messages from workers through its task queue. Both are managed by the event loop.)
The event loop is a while loop that continuously monitors the task queue. If there are tasks remaining in the queue, the event loop retrieves (dequeues) and executes them. For example, if the task is related to a click event, the event loop creates a MouseEvent
object at the time of task execution and executes the event handler connected to this event. If there is no handler, nothing happens. The time at which the MouseEvent
object is created is stored in event.timeStamp
. (PerformanceEntry.startTime
also records this time and has a value almost identical to event.timeStamp
. However, PerformanceEntry
is used for a wider range of performance measurements.)
The main thread of a web browser performs many tasks, including HTML parsing, CSS processing, JavaScript execution, and handling user events. Therefore, each event handler should be written as short and efficient as possible. If an event handler performs too much work, the web page's responsiveness will suffer, degrading the user experience. Users expect a response time of within 200ms, and longer times can make them feel that the page is unresponsive. Especially in the case of web applications where immediate responses to user inp
Reference: Tasks, microtasks, queues and schedules - JakeArchibald.com