Event loop and async javaScript
JavaScript is a single-threaded language
As we know JavaScript is a single-threaded language, it has only one call stack to execute a code line-by-line, and there is no plan to become a multi-threaded language.
JavaScript is a single-threaded language but javaScript behaves like a multi-threaded language, This is because of its Async, No blocking behavior.
Event Loop
Event loop is a mechanism to handle asynchronous code, To perform code execution efficiently, Event loop comes with one call stack, browser APIs, macro task queue or task queue, and micro task queue.
Call Stack: It is single-threaded, means it can only do one thing at a time, Code execution is synchronous, A function invocation created a stack frame that occupies a temporary memory, It works as a LIFO - Last In First Out data.
The call stack is a line-by-line JS code executer container. It takes the name function, processes that code, and show to a client in the front end.
Browser APIs: It is placed in the browser to work with browser-related API calls, They interact with the browser take what they want, and go to a macro task queue, and wait for an empty call stack.
Some of the browser APIs are:
setTimeout
,setInterval
,setImmediate
, HTTP request.
Macro Task Queue or Task Queue: A macro task queue makes a single-threaded JS language behave like a multi-threaded, In this task queue code coming from browser APIs after interacting with the browser, executable code seat until a call stack and micro task queue gets empty.
Task Queue handle:
setTimeout
,setInterval
,setImmediate
, HTTP request, I/o operation, UI rendering,
if (call stack && microtask === "") {
return "execute task queue"
}
Micro Task Queue: A micro task queue handles JS code asynchronously without blocking anything, It also prioritizes over task queue mense when the call stack gets empty micro task queue pending code sent to a call stack to execute over task queue.
Micro Task handle: Promise handlers
.then()
,.catch()
,.finally()
,queueMicrotask()
, Mutation observer.
Subscribe to my newsletter
Read articles from Saurabh Tajane directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by