What is a call stack ?
A call stack is a mechanism for an interpreter (such as a JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions - which function is currently running and which functions are being called from that function, etc. — MDN Web Docs
The call stack keeps record of the all functions to be executed. When a function is called , it is added on to top of the call stack. When the function returns, it is removed or removed from the call stack. Any asynchronous functions (fetch, setTimeout, async, etc.) are moved to the event queue (more on that later).
How does the call stack work?
As JavaScript is single-threaded. This means that it has only one call stack and can only handle one command at a time. The call stack follows the LIFO (Last In, First Out) principle, which means that it always processes the call at the top of the stack first.
When a function is called, it is added to the stack. When a function calls another function, it is added to the calling function.
Callback queue
When the browser is done with the timer (or any other API which it provides for JS), it doesn't transfer the codes to be executed back to Javascript immediately. When the browser finishes, it adds the code in a callback queue. As the name implies, it is a queue containing some functions or codes which would be called back at a later time.
The callback which was passed as an argument to setTimeout is written in JavaScript. So the JavaScript interpreter needs to run the code, which means it needs to use the call stack, which again means we have to wait for the call stack to be empty to make the callback.
The setTimeout call triggers the Web API execution, which adds the callback to the callback queue. The event loop then takes the callbacks from the queue and adds them to the stack once it's empty.
Event Loop: This is followed by an Event Loop which runs continuously and checks the main stack if it has any frames to execute, if not it checks the callback queue, if the callback queue has codes to execute then it pushes the message from it to the main stack for execution .
Job Queue: In addition to the Callback Queue, browsers have introduced one more queue, which is the "Job Queue", reserved only for the new Promise() function. So when you use promises in your code, you add a .then() method, which is a callback method.
Top comments (0)