- Start execution using the main thread referred to as main() here.
- Identify the function which needs to executed and add it in the call stack.
- Identify other function which the current function executes and add it in the call stack.
- Upon completion of the function remove its reference from the call stack.
- Repeat steps #2 to #4 till the code finishes execution.
- After all the code has finished execution, remove main() from the call stack.
Async call stack
To solve this we write asynchronous code which performs time consuming operations in the background without blocking the main thread and uses callback mechanism to resume code execution.
setTimeout is one such mechanism.
setTimeout which will run the function passed to it after at least 5 seconds. The main thread executes
- WebAPIs: APIs like setTimeout, setTimeInterval are provided by the browser. These APIs are responsible to add callbacks in event queue. For eg.
setTimeout(cb, 5000)will add the callback function
cbin event queue after the 5 seconds.
- Event Queue: Event queue contains functions which are to be added in call stack by event loop.
- Event Loop: Event loop is responsible to push the functions available in event queue to the main call stack. Event loop pushes a function only when the call stack is empty.
Event loop is browser’s mechanism to perform non blocking operations. It does that by providing webAPIs (eg. setTimeout) which are capable of maintaining callback references in memory. The callbacks are added to event queue depending on the logic of the webAPI (for eg. setTimeout waits for n milliseconds, XMLHTTPRequest waits for ajax call to finish). Event loop adds callback from the event queue and pushes it to the call stack where the callback is executed.