Execution Call StackA data structure for the interpreter to keep track of its place in a script that calls multiple functions. It is single threaded and LIFO (Last In First Out)
Web APIsBuilt in APIs that have a separate execution context from your code (They act as separate threads) examples include
Callback QueueA data structure that holds functions returned from Browser APIs that are ready to go back on the stack. It is FIFO (First In First Out)
Event LoopMiddleman between callback queue and call stack. Checks if call stack is empty and adds functions from the callback queue
Using sticky notes in this Jamboard, answer the following with your breakout group:
- Everything you know about & questions you still have on asynchronous code
- Everything you know about & questions you still have on fetch
- Everything you know about & questions you still have on execution contexts & the call stack
On Your Own
Then in breakout groups, explore this site that gives a nice visualization of how asynchronous code runs in the browser. Note the call stack as well as the Web API the article discusses.
- When running the code, note where the
console.logsare moved. What about the
- Where does the
setTimeoutmove to before going back to the call stack? What do you think this callback queue is?
- Click on the Click Me! button on the bottom left-hand corner. Discuss the order of events.
With Your Partner
Given the following code snippet:
console.log('ramen'); fetch("https://opentdb.com/api.php?amount=1&category=27&type=multiple") .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.log(error)); console.log('burrito');
- How does
fetchfit in with the code above and below it?
- What order will the console logs show up in and why?
- Using terms like the call stack, Web API, & callback queue, explain this is working behind the scenes.
Call Stack and Event Loop
On Your Own
Let’s take a look at this video that has some great visualizations for the call stack, event loop, and queue. Pay close attention during the following points:
- 4:15-6:00 (call stack with synchronous functions)
- 6:40 (stack overflow example)
- 7:20-8:50 (imagine if
fetchwere synchronous - we would have to wait for each request to complete before moving on)
- 10:23-11:46 (asynchronous callbacks -
setTimeout, what happens to the
setTimouton the stack?)
- 11:47-14:50 (intro to the event loop)
Please take notes and pay special attention to the vocab words at the top of this lesson as you watch
Check for Understanding
- Review how the call stack works with synchronous events?
- What is involved with asynchronous events such as
- Describe the relationship the
event loophas with the