GENERAL GOAL
I’d like to know how the following pieces of a javascript environment interconnect as a system.
- Javascript Engine
- Event Loop
- Event Queue
We can limit this to a browser environment since node has been covered in another article (here)
THINGS I (believe to) UNDERSTAND:
Javascript is single threaded and therefore only has one callstack.
Javascript environments provide only a few functions that are truly asynchronous. These may include setTimeout(), setInterval(), and I/O function(s).
- A developer cannot create their own asynchronous functions without using one of these.
- Javascript itself runs synchronously but through it’s async functions can callback the would-be blocking functions once the current callstack is clear.
EXAMPLE:
console.log(‘Sync code started…’);
setTimeout(function asyncLog() {
console.log(‘Async function has completed’)
}, 2000);
console.log(‘Sync code finished…')
EXAMPLE STEPS:
( Please correct steps if I’m wrong )
- ‘Sync code started…’ is logged
- setTimeout is added to stack but immediately returns control
- setTimeout is sent to a different ‘thread’…’worker’? outside of javascript’s single thread to count the 2000 milliseconds
- ‘Sync code finished…’ is logged
- After 2000 milliseconds asyncLog() is pushed to the Event Queue
- Because the callstack is clear the Event Loop checks the Event Queue for pending callbacks
- asyncLog() is removed from the queue and pushed to the stack by the Event Loop
- 'Async function has completed’ is logged
- callstack is now clear
QUESTIONS
These don’t need to be answered one by one if someone could produce an overview of the steps of how and where async functions (such as setTimeout) go from the time they first hit the callstack to when they are called back to the callstack.
- On step 3, who produces this new thread? Is it the browser?
- This new thread is being blocked correct?
- What happens if you have a loop that creates 1000 setTimeouts. Are 1000 ‘threads’ created?
- Is there a limit to how many threads can be spawned at a time?
- When new thread finishes executing, how does it end up on the queue?
- Who supplies the Event Queue?
- Who supplies the Event Loop?
- Does the event loop poll the Event Queue?
- Is the javascript’s thread aware of an event loop? Or does the Event loop just push things onto the stack?
- How does the Event loop know when the stack is clear?