DOM Events and the Event Loop

Alex Reardon
InstructorAlex Reardon

Share this video with your friends

Send Tweet
Published 6 months ago
Updated 5 months ago

This lesson presses into the deep inner workings of the event loop in order to understand how events fit into the overall javascript execution lifecycle.

Instructor: [0:00] Here is a simplified diagram of how the event loop works in JavaScript. On our call stack is the code that is currently executing. All JavaScript is executed in the call stack. The call stack is our single execution thread.

[0:13] We also have multiple task queues. Task queues contain an ordered list of tasks that are waiting to be executed in the call stack. There are different task queues for different types of tasks.

[0:24] For example, there might be one task queue for callbacks and another for events. Browsers are free to define what these different task queues are. It is the job of the event loop to take a task off one task queue and move it over to the call stack to be executed.

[0:40] The event loop is constantly checking the task queues for new tasks to be run. It is up to browsers to decide which task queue to prioritize pulling tasks from. The event loop is also responsible for coordinating UI rendering tasks.

[0:54] Web APIs can add tasks to a task queue. For example, when you write setTimeout() and you pass in a callback function and the number 100, that will ask a web API to create a task to invoke the callback function after waiting 100 milliseconds.

[1:11] After 100 milliseconds, a task to invoke the callback is added to a task queue. Eventually, the invoked callback task reaches the front of the task queue and is picked up by the event loop and is executed in the call stack.

[1:25] When an event is occurring in the browser, a web API creates a task for the event and adds it to a task queue. Eventually, the task is picked up by the event loop, given to the call stack, where all the event listeners for that event will be executed.

[1:41] If you have a long-running task in the call stack, that task blocks other tasks from being picked up, including tasks for events. For input events, this can cause input delay for your users.

[1:56] In the same way, if you are doing a lot of expensive work in your event listeners, then your event task can prevent other tasks such as callbacks and other events from being picked up by the event loop and executed in the call stack.