Based on awesome talk by Philip Roberts and this Medium article
JavaScript is a single-threaded single concurrent language -> can only execute one task at a time, one piece of code at a time.
Single call-stack + heap + queue = Concurrency Model
Data structure that records the function calls as a stack of frames. When a function is called, it is pushed onto the stack and when it returns, it is popped off the stack.
In the above gif, we can see that we start by adding the console.log(bar(6))
to the stack because this is where the function is called first.
bar
is then added onto the stack which calls foo
.
When foo
returns, it is popped off the stack and same for bar
afterwards.
When an error happens, the stack trace can be viewed in the browser console. It indicates where we were in the call stack when the error happened.
The limit size of the stack trace is 16,000 frames.
Memory where objects are added and allocated.
The JavaScript runtime contains a message queue, a list of messages to be processed and callback functions to execute. When the stack is empty, the event loop will take messages from the callback queue and add them onto the call stack to be executed.
The setTimeout
function is usually called with 2 arguments, a message to add to a queue and a time value in milliseconds. This time value represents the minimum delay after which the message will be executed.
However, if there are already messages in the queue, the delay will be more than the time value indicated as it will have to wait for the other messages to be executed first.