Agenda:
- JavaScript Introduction
- Call Stack Introduction
- Asynchronous Callback
- Task Queue
- Event Loop
1 JavaScript introduction
- JavaScript is a single threaded, non-blocking, asynchronous concurrent language.
- It has a call stack, an event loop and a callback queue + other APIs.
- V8 is the JavaScript engine which has a call stack and a heap.
- The heap is used for memory allocation and the stack holds the execution context.
2 Call Stack Introduction
A call stack is a mechanism for an interpreter (like the JavaScript interpreter in a web browser) to keep track of its place in a script that calls multiple functions — what function is currently being run and what functions are called from within that function, etc.
Example:-
1 . Let’s suppose we have a function “greeting”, “sayHi” and we’ve to invoke the “greeting”.
function greeting() { sayHi(); } function sayHi() { return "Hi!"; } // Invoke the `greeting` function greeting();
2. Know greeting will be include in Call Stack.
3 . We call “SayHi” inside the “greeting()” so “sayHi()” will be included in the call stack.
4 . “greeting” is steel running and “sayHi” return “Hi!”.
5 . All the execution context of “sayHi” will be destroyed And “sayHi” will be thrown out.
5 . And finally “greeting” will be thrown out.
3 ASYNCHRONOUS CALLBACK
- Sometimes the JavaScript code can take a lot of time and this can block the page render.
- JavaScript has asynchronous callbacks for non-blocking behaviour.
- JavaScript runtime can do only one thing at a time.
- Browser gives us other things which work along with the runtime like Web APIs.
- In node.js these are available as C++ APIs.
4 TASK QUEUE
- JavaScript can do only one thing at a time.
- The rest are queued to the task queue waiting to be executed.
- When we run setTimeout than web APIs will run a timer and push the function provided to setTimeout to the task queue once the timer ends.
- These tasks will be pushed to the stack where they can executed.
5 THE EVENT LOOP
- JavaScript has a runtime model based on an event loop, which is responsible for executing the code, collecting and processing events, and executing queued sub-tasks.
- The event loop pushes the tasks from the task queue to the call stack.
- We can see how these things work in action :
If you need custom WordPress Development services then feel free to reach us.
!!Have a Great Day Ahead!!
1 comments