Introduction
In javascript we have an amazing quantity of libraries, tools and such things that make our work easier, but did you ever try to understand how it is working under the hood? Javascript is a widely spread language so many of us got attracted and want to use higher level tools without understanding its deep working which is not the right way. You should always know how your code actually got executed.
Today we will see how callbacks will be executed in javascript. We all know javascript is single threaded. We also know that it supports asynchronous behaviour. But this behaviour is not part of javascript. This asynchronous behaviour access through browser APIs which are built on the top of javascript.
Simple Javascript – Example
First let’s see how simple javascript code get executed.
You can see it is running line by line. Javascript is single threaded so
One thread == One call stack == One thing at a time and so we have one call stack.
Event Loop
Heap –
It is just a memory allocation thing.
Call stack –
It is a data structure which records, where in the program we are. If we step into the function, we push something into the stack and if we return from the function, we pop of from the stack.
Web APIs –
They are not the part of javascript but are they are built on top of the core javascript language, which gives you extra features to use in your javascript code. For example setTimeOut gives you some simple features that you can prevent some code from getting executed for defined time.
Callback queue –
When you call setTimeOut or any async operation, Web APIs will add them to callback queue. This is also a data structure. It’s work is to store functions in correct order
Event Loop –
This is a constantly running process which checks if call stack is empty or not? If yes then it will execute the function from callback queue. So remember, callback function only get executed if call stack is empty. Always make sure that all callback functions should get chance to enter in call stack.
Event Loop – Example
If you set time to 0 in setTimeOut, it will still run on the last. This time does not stand for time delay after which function will execute, this time is the minimum time function need to wait.
So, this is it for now. Keep doing meaningful code. Keep searching for deep working of any functionality you use.