- In this, the user tries to access the data which is available in different segments of the code (like in different functions or methods), which are interrelated to each other or interdependent with each other.
- The concept of Call Stack comes into the picture, which is a stack that follows LIFO (Last-In-First-Out) structure wherein every function of task is executed by removing anything which is present at the top of the stack itself.
First function Execution Starts..... GeeksforGeeks.... Second Function execution is completed..... First Function execution ends here.....
Working of the above Synchronous code is explained with the help of the following pictorial representation of Call Stack.
- Every element is removed from the top of the stack and when it is removed it gets printed in the browser’s console.
- This is how synchronous code actually works whenever different functions are called with their respective data execution too.
- This generally took place whenever the user tries to fetch the data from the API (Application Programming Interface) resource or tries to collect the response from the API itself.
- To handle the asynchronous data, we use promises or callbacks which helps users easily fetch responses or data from the API with ease.
- After understanding the basics of Call Stack, some more technical concepts exist like Event Loop, Web API, and Message Queue.
- Whenever any synchronous method or DOM events (like setTimeout or promises or callbacks) comes into the existence, it gets executed into the Web API’s and after its timer gets completed it is pushed into the message queue from where the event loop further pushes that message into the Call Stack for its execution.
- The task which Event Loop executes is basically determining whether or not the stack is empty. If it is empty then that particular event loop takes data from the message queue to Call Stack for execution.
Program Starts...... Program Ends..... Promise resolved..... setTimeout execution....
Program Starts...... Program Ends..... Promise 1 resolved..... Promise 2 resolved..... setTimeout 1 execution.... setTimeout 2 execution....