Today I Learned - Rocky Kev

TIL the difference in the JS Event Loop for Browsers and Node

POSTED ON:

TAGS:

It took me years to understand this. Someone saying that "they use Javascript" could mean they use Javascript on the web, or Node, or a different Javascript environment, of which there are MANY!

This is a small explainer of the differences in how Javascript functions get fired.

The Event loop in the browser

Heap - It stores all the object reference and variables that we define in our function.

Call Stack - This holds our function calls.

Web API's - Special API's are provided by browser which provides additional functionality over V8 engine.

Queues - There's two types of queues. The macrotask queue (sometimes called the callback quque) and the Microtask queue (sometimes called the job queue).

Macro-Task Queue (Callback quque) - This is the main queue.

Microtask Queue (Job Queue) - This queue executes async functions which uses promises and has higher precedence.

The Event Loop in Node

In Node, it's a bit simplier.

Event Queue - This is where events get added while they wait to be processed.

The Event Loop - This is the main loop (main thread).

   ┌───────────────────────────┐
┌─>│           timers          │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │
│  └─────────────┬─────────────┘      ┌───────────────┐
│  ┌─────────────┴─────────────┐      │   incoming:   │
│  │           poll            │<─────┤  connections, │
│  └─────────────┬─────────────┘      │   data, etc.  │
│  ┌─────────────┴─────────────┐      └───────────────┘
│  │           check           │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │
   └───────────────────────────┘

via NodeJs guide

Thread Pool - This is where the more "expensive" tasks. This is also known as the Worker Pool.

Difference between the Event Loop in Browser and Node Js?

The Node.js Event Loop, Timers, and process.nextTick()


Related TILs

Tagged:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.