Use the Cooking Game website to analyze and break down how the JavaScript event loop works using a cooking analogy.
Here’s a step-by-step explanation of how the event loop processes a promise:
-
Initial Execution
- The JavaScript engine starts running the code from top to bottom.
- Each function call is pushed onto the call stack.
- If a promise is created with
.then(), the executor function of the promise runs immediately and synchronously. - Any asynchronous work inside the promise (e.g. network request) is handled by Web APIs.
-
Promise Executor
- If the promise resolves or rejects, its callback handlers are added to the microtask queue.
-
Call Stack Execution
- The call stack finishes executing any remaining synchronous code until it is empty.
-
Microtasks Execution
- Once the call stack is empty, the event loop moves to the microtask queue.
- All microtasks (like promise callbacks) are executed before the event loop continues to the task queue.
-
Task Execution
- After all microtasks are cleared, the event loop processes tasks in the task queue, such as:
setTimeoutsetInterval- I/O callbacks
- After all microtasks are cleared, the event loop processes tasks in the task queue, such as:
-
Make a Copy
Create a personal copy of this assignment to work on. -
Review the Event Loop
Watch this video to refresh your understanding:
What the heck is the event loop anyway? | Philip Roberts | JSConf EU -
Navigate to the Cooking Game
Open the following in your browser:
🔗 Cooking Game -
Play the Game
Observe the sequence of events while cooking pasta. Pay attention to what happens when. -
Break Down the Cooking Steps
Match each cooking action to an event loop concept:- Initial Execution
- Promise Executor
- Call Stack Execution
- Microtasks Execution
- Task Execution
-
Add Two Extra Steps
Think of two additional tasks (e.g. washing dishes, setting the table).
Identify where they would fall in the event loop sequence. -
Identify
setTimeoutorsetInterval
Reflect on where these might be used in the game and how they relate to the task queue.
| Event Loop Step | Purpose of the Event Loop Step with Cooking Analogy as Example |
|---|---|
| 1. Initial Execution | |
| 2. Promise Executor | |
| 3. Call Stack Execution | |
| 4. Microtasks Execution | |
| 5. Task Execution | |
| Extra Step 1 | (e.g. Washing Dishes) |
| Extra Step 2 | (e.g. Setting the Table) |
- Write your responses directly in the table above using complete sentences.
- Turn in the link to your Google Doc via Canvas.
- Set sharing access to "Restricted" and add your instructional staff as collaborators.
- Use the "Share" button at the top right of your document to adjust access.
Happy coding (and cooking)!