Javascript
Event Loop

What is Javascript's Event Loop?

JS is a single threading programming language so it has a single call stack. (we don't want to block this single thread)

The event loop helps JS do appear to be multi-threaded by handling asynchronous behavior. (Processes can now run concurrently, but not in parallel)

The browser gives us some features that the JavaScript engine itself doesn’t provide: a Web API. This includes the DOM API, setTimeout, HTTP requests, and so on. This can help us create some async, non-blocking behavior by letting us delay tasks without blocking the main thread.

When we invoke a function, it gets added to something called the call stack. The call stack is part of the JS engine, this isn’t browser specific

Callback functions that has been resolved will be added to a queue (not the stack)

The only task of the event loop is to connect the queue with the call stack.

If the call stack is empty (aka if all previously invoked functions have returned their values and have been popped off the stack) the first item in the queue gets added to the call stack.

Microtask Queue vs Macrotask Queue

  • The main difference between microtask and macrotask queue is their priority. The event loop always gives higher priority to the microtask queue, and will process all the callbacks in the microtask queue before moving on to the macrotask queue.
  • The microtask queue contains the callbacks of operations that are considered more urgent or important, such as promises and mutation observers APIs.
  • The macrotask queue contains the callbacks of operations that are less urgent such as timers, I/O events, and user interface events

Resources that helped me understand this clearly