

JavaScript — Call stack , event loop and callback queue
source link: https://dev.to/imkarthikeyan/javascript-call-stack-event-loop-and-callback-queue-1ioo
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.


JavaScript — Call stack , event loop and callback queue
When I started as a beginner in JS, I had some difficulties in figuring out the concepts which I am about to say. I think I have figured it out. Thanks to talk given by Philip Roberts at JS conf EU. I will be sharing the things which I understood in the below article. This article will be about how the javascript program works under the hood.
First things first , what is Javascript ?
Javascript is a single threaded, non-blocking, concurrent and asynchronous language. It has single call stack and executes the program concurrently. But how ? Let’s talk about that. I will be starting with some of the terminologies which will clear your doubts.
- call stack
- callback queue
- event loop
Call Stack :
CallStack is generally a data structure which consists of active sub-routines in the computer program. So when a program executes, if it sees a function call, then it is pushed onto the stack and once the function finishes the execution or returns a value, then it will be popped out from the stack.
let’s see how a below piece of code is being executed by JS behind the scenes.
console.log("data");
function foo(){
console.log("foo");
}
function bar(){
console.log("bar");
foo();
}
bar();
Let's see a video which shows the execution of the program
After we run the program , console.log("data")
and since it returns value data
it will be popped out from the stack. Followed by that, bar()
gets pushed onto the stack which in turn prints inside console.log()
function which is present inside the bar()
function definition. After this foo()
gets pushed onto the stack which in turn executes console.log("foo")
then pops the foo
from the stack and finally bar
gets popped off from the stack
Call stack ( total call stack frames 16000 ) goes out of the range in case of the recursive function call which might be caught in the endless loop.
Heap:
Objects are allocated in a heap which is just a name to denote a large mostly unstructured region of memory.
Call back queue :
Call back queue or message queue contains the list of messages to be processed and their associated call back functions. The messages are queued in response of an external events ( Like response after ajax call or response from the click event ) . As the external events are web apis which are not part of the V8 runtime , when the call stack encounters it pushes to another block where it starts to execute and pushes to callback queue when it receives the response or the timer is finished.
As you can see from the above screenshot, set timeout function executes for 500ms
then it pushes to call back queue which it turn pushed on to the call stack by the technique called event loop
which we will talking about soon.
Since there is no console.log()
messages inside the call back , it will just execute the callback in the settimeout
function after 500ms.
Event loop:
Event loop is a simple piece which puts the whole puzzle together. So when the set timeout or click function
is called or when pushed on to the stack , after the execution it goes to the callback queue. So the event loop will be checking the call stack and the callback queue
. If the call stack is empty , then it pushes the first processed callback function present in the callback queue to the call stack. Each message is processed completely before any other message is processed.
while (queue.waitForMessage()) { queue.processNextMessage(); }
queue.waitForMessage()
waits synchronously for a message to arrive if there is none currently.
In web browsers, messages are added anytime an event occurs and there is an event listener attached to it. If there is no listener, the event is lost. So a click on an element with a click event handler will add a message — likewise with any other event.
The function set timeout
function has two arguments which has two arguments which will be the message to add it to the queue and the time value ( default : 0 ). The time value represents the (minimum) delay after which the message will actually be pushed into the queue.
If there are no messages in the queue then , the message will be processed right after the delay. If there are messages in the queue , then it will have to wait for the previous messages to be processed. For that reason, the second argument indicates a minimum time and not a guaranteed time.
Conclusion:
That's pretty much it. Thank you for taking the time to read the blog post. I hope , everyone understood how the javascript program works under the hood and also about the asynchronous part. If you found the post useful , add ❤️ to it and let me know if I have missed something in the comments section. Feedback on the blog are most welcome.
Let's connect on twitter : (https://twitter.com/karthik_coder)
Useful resources:
Recommend
-
6
Call waiting versus callback verifier systems Here's one for the "problems nobody should have any more" category. Back in the '80s, my dad would occasionally be on call for his company. They had issued a terminal and modem that...
-
7
Stack and Queue in JavaScriptLearn about two important data structures—stack and queue—and how to implement them in JavaScript. Every time we are developing a new application, there are certain topics that we should think through first...
-
7
Understanding JavaScript Event LoopJuly 19th 2021 new story6
-
5
Ever - a callback-less event reactor for Ruby Ever is a libev-based event reactor for Ruby with a callback-less design. Events are emitted to an application-provided...
-
12
JavaScript的事件队列(Event Queue)宏任务和微任务时间: 09/07/2020作者: ll浏览量: 1027在写代码的时候经常思考一个问题,到底是那个函数先执行,本身JavaScript是一门单线程的语言,意思就是按照顺序执行...
-
7
Not FoundYou just hit a route that doesn't exist... the sadness.LoginRadius empowers businesses to deliver a delightful customer experience and win customer trust. Using the LoginRadius Identity...
-
7
JavaScript & Node事件循环机制(Event Loop)2020-01-18计算机原理作为一枚“前端打字员”,...
-
5
JavaScript Event Loop、Micro Task、Macro TaskEvent LoopEvent Loop:事件循环、Micro Task:微任务、Macro Task:宏任务我们知道 JavaScript 是单线程语言,一心不能二用,也就是说它只能把一件事干完才能去干另一件事,但前端的一...
-
6
Meta Adds Enhancements for Call Ads, Including New Callback Option Published Sept. 28, 2022 By
-
6
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK