The aim of the post is to give a simple, concise, and high level description of the event loop. I’m intentionally leaving out many details and being somewhat imprecise.
If you need detailed picture, follow the links in this post. In this case, I recommend reading this short post first.
Why Event Loop?
To deal with concurrency (multiple “things” need to be happening at what looks like the same time), there are few models. To discuss the models, we need to know what a thread is.
Roughly, a thread is a sequence of computing instructions that runs on a single CPU core.
Roughly, Event Loop manages on which tasks the thread works and in which order.
The queue contains what’s called in different sources messages, events, and tasks.
Message/event/task is a reference to a piece of code that needs to be scheduled to run. Example: “the code responsible for handling the click of button B + full details of the click event to pass to the code”.
- The queue is checked for new tasks. If there is none, we wait for one to appear.
- The first task in the queue is scheduled and starts running. The code runs till completion. In many languages,
awaitkeyword in the code counts as completion and everything after
awaitis scheduled to run later – new task in the queue.
- Repeat from number 1. That’s the loop. It’s called Event Loop because it processes events from the queue in a loop.
Adding Events to the Queue
Tasks are added to the queue for two reasons:
- Something happened (user clicked on a button, network packet arrived, etc).
- The code that was running in step 2 of the event loop scheduled something to run later.
- Event Loop documentation at MDN.
- What is the difference between concurrency and parallelism? at StackOverflow
Hope this helps with high level understanding of Event Loop. Have a nice day!