Call Stack, Event Loop, and Task Queue

Anish Giri
jsninja
Published in
3 min readNov 25, 2018

Hey there Ninja’ s, hope you all are doing well. Today, lets discuss on some behind the scene concepts of JavaScript. I always had curiosity on the internal workings of JavaScript. I was always like, how the hell is this working ?. Then upon some research, I came to know about the CallStack.

CallStack is a data structure which keeps track of function calls in our program. When ever we call a function for its execution, we are pushing it to the stack. It is popped out of the stack when the execution is completed.

Here, we can see the call stack in action. First, the main thread kicks in, then the call to the bazinga function is pushed to the stack, following it function bar is called inside the function bazinga, it is also pushed onto the stack. Similarly function foo is called inside bar and it is also pushed to the stack. Now as the execution of function foo is completed, it is popped out from the stack first and then bar is popped out followed by bazinga popping out. And at last the main thread also pops out. So this is how Synchronous code is executed in JavaScript.

Task Queue (Micro task Queue) is a JavaScript runtime messaging queue which handles task that is allocated by different Web Apis. This queue is dedicated to handle the Web Apis callbacks. The message are processed once the call stack is clear.

Event Loop has pretty specific work. It has responsibility to see weather the call-stack is empty and does the task queue contains pending task to process. If the call-stack is empty, it will push the task to the call-stack from the queue and the task gets processed.

In the above gif we can visualize how async operation is done in JavaScript. Here are three boxes and they have their own definite roles for async operations. The left box is CallStack , which we just completed discussing on. The right box are the Web APIs’ (such as setTimOut SetInterval and browser events ). And the box beneath is the Task Queue. There is also a blue wheel like thingy there, which is Event loop.

Here first the main thread kicks in and then foo gets pushed to the stack and immediately gets popped out when the execution is completed. Now setTimout gets executed and then it disappears until the timer done. Right after that bar gets pushed onto the stack without any blockage and gets popped out once its execution is complete. Now as soon as the timer is done the call back concerning to timeout function is pushed to queue. The Event loop is continuously looking for the task queue and the status of the stack. As it finds the call-stack empty, it pushes the task to the stack from the queue. Then again the main thread kicks in and the call back gets executed and gets popped out from the stack. At last the main thread pops out.

Ok then thats it for now. Hope this article was helpful. See you in next article. Cheers !!!! :).

--

--