Event loop
August 16, 2021
Content |
---|
Event loop |
Callstack & tasks queue |
JS runtime and web APIs |
JS environment
This is a brief/general overview of what the event loop
is, and what it does. JavaScript is a single threaded synchronous interpreter/compiler, and this means that things happen one at a time.
If you've ever wondered how it is, that a single-threaded and synchronous compiler like JavaScript is
capable of executing code in an asynchronous manner or how is it that the web APIs
responsible for manipulating the DOM, and fetching data have nothing to do with JavaScript - the language - while
at the same time essential for giving JavaScript its multi-threaded capabilities. It is partly because of the event loop
.
Synchronous code execution below. The interpreter executes x and y before calling the add function
, and followed by var z.
let x = 10;
let y = 50;
console.log(add(x,y));
let z = 100;
const add = (x,y) => x + y;
It is a single-threaded language at runtime. This means code execution is done one piece of code at a time. Any code that takes longer time than usual is basically blocking the path for other code to be executed.
Event loop
Each browser has its own version/flavour of a JavaScript engine
, and event loop
that watches over the call stack
, and tasks queue
. Most popular being Google's V8 engine used in Chrome and Node.js.
But the browser is more than just a runtime
, it also provides the web APIs
that function like threads and are needed for async like behaviour. In other words, without the browser JavaScript wouldn't be able to run code asynchronously.
We make calls to access these web APIs
, and in return callbacks
are dispatched to the event queue
where they'll remain in turn-ready to be pushed onto the callstack
by the event loop
. Once inside the callstack
, it is executed and a value returned.
The event loop, like the MutationObserver
in the DOM, it watches for changes in the callstack
, and so when it's empty it places the first task in the queue onto the stack again for processing, and removes it from the stack once it has returned/completed processing.
Callstack
About Callstack
- It's responsible for keeping track of all the operations awaiting execution.
- It can also show which block of code is currently being read by the JS interpreter
- First-in, first-out mode. (Synchronous code)
- Whenever we step into a function, we're putting something on the stack,
- Whenever we return from a function, we're taking it off the stack.
Async code is handled differently. It gets forwarded to the events table to be handled by the browser's APIs
Tasks queue
Whenever an async task completes, the callback function
associated with the async task gets pushed
into the tasks queue
; where they await callstack
execution.