Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSamuel Kleos
Front End Web Development Techdegree Student 13,581 Points1. Do multiple Web APIs manage one callback queue 2. When does event loop prioritise tasks in the queue?
Clarification 1: I am looking to identify the mutually exclusive factors that identify whether a task is located in the Web API vs in the Callback Queue.
The instruction mentions the following factors "You can think of the callback queue as a holding area for all the callbacks that are waiting to be put on the call stack and eventually executed. Only callbacks for (non-blocking) operations that are scheduled to complete execution at a later time"
Contrary to the above, the graphic depicting the callback queue shows the setTimeout callback waiting for 1s in the Web API box. It would seem that the Web API is the 'holding area'.
"After the 1000ms delay is up, func2 moves to the callback queue where it waits to be pushed onto the call stack."
"The web APIs add each async task to the callback queue where they wait to be pushed onto the call stack and executed one at a time."
How is the Web API adding the async tasks to the callback queue? How can multiple APIs add their tasks to one callback queue?
Clarification 2: "Anytime the call stack is empty, the event loop takes the first task from the callback queue and pushes it onto the call stack, and runs it."
What if the call stack is never empty? Doesn't that mean this code will be executed last? If so, just add it to the bottom of the js file instead right?
1 Answer
Steven Parker
231,269 PointsThe Web API is where the async operations are taking place, it's not a 'holding area'. It might appear to be one if the async operation in question is simply a timer.
Without looking "under the hood" into the JavaScript engine, we can't be sure how the async tasks are added to the callback queue. But we can guess that involves a mutex or semaphore of some type. It's the nature of these mechanisms to accept requests from multiple sources.
And just moving some code to the bottom of the program doesn't insure that the event it is intended to handle would have occurred, like a certain amount of time has passed or the result of an AJAX request has been received.