Tutorials

Understanding the JavaScript Event Loop

Why does JavaScript feel single-threaded yet handle so much at once? The event loop is the answer. Here's a clear mental model with examples you can run.

Takina Takina · · 1 min read
Lycoris lily illustration

JavaScript runs on a single thread, yet it juggles network requests, timers, and clicks without freezing. The mechanism that makes this possible is the event loop. Understanding it explains a lot of “why did that run in that order?” surprises.

The pieces

  • Call stack — where functions execute, one at a time.
  • Web APIs — browser (or Node) features like timers and fetch that do work off the main thread.
  • Task queue (macrotasks) — callbacks waiting to run, e.g. setTimeout.
  • Microtask queue — higher-priority callbacks, e.g. resolved Promises.

The event loop’s job: when the call stack is empty, run everything in the microtask queue, then take one task from the task queue, and repeat.

A classic example

console.log("1");
setTimeout(() => console.log("2"), 0);
Promise.resolve().then(() => console.log("3"));
console.log("4");

The output is 1, 4, 3, 2. Synchronous code runs first (1, 4). Then the loop drains microtasks (3, the Promise) before macrotasks (2, the timer) — even though the timer was set to 0.

Why microtasks beat timers

After each task, the loop empties the entire microtask queue before moving on. So Promise callbacks always run before the next setTimeout. Chaining lots of microtasks can even starve timers — something to watch for in tight loops.

Practical takeaways

  • setTimeout(fn, 0) does not run immediately — it waits for the current work and all microtasks to finish.
  • await is Promise-based, so continuations after await are microtasks.
  • Long synchronous work blocks everything, including rendering. Break it up or move it to a Web Worker.

Once you picture the stack draining, then microtasks, then one macrotask, the ordering stops being mysterious.

Tutorial · 3 min read

Getting Started with TypeScript: A Practical Guide

TypeScript adds a safety net to JavaScript without slowing you down. Here's how to set it up, the handful of concepts that matter, and how to adopt it gradually.

#TypeScript #JavaScript #Web Development
Tutorial · 1 min read

HTTPS Explained: What Happens When You Visit a Site

The padlock in your address bar hides a clever handshake. Here's what actually happens when you load an HTTPS site — encryption, certificates, and trust.

#Security #Networking #Web Development
Tutorial · 1 min read

CSS Grid vs. Flexbox: When to Use Each

Grid and Flexbox aren't rivals — they solve different problems. A simple rule of thumb, with examples, for choosing the right layout tool every time.

#CSS #Web Development #Frontend