If you’ve ever logged “A, B, C”… and got “A, C, B” in JavaScript, the event loop just taught you a lesson. ⚙️🧠 Here’s the mental model that stops a lot of “why is my UI stale?” and “why did this run before that?” bugs: Macrotasks (task queue) ✅ - setTimeout/setInterval - DOM events - I/O (in browsers/Node variants) Microtasks (microtask queue) ⚡ - Promise.then/catch/finally - queueMicrotask - MutationObserver Rule of thumb: After a macrotask runs, JS drains ALL microtasks before it picks the next macrotask. So this: console.log(1) setTimeout(()=>console.log(2)) Promise.resolve().then(()=>console.log(3)) console.log(4) prints: 1, 4, 3, 2. Why you should care (real-world): • React/Next.js: state updates and effects can “feel” reordered when you mix timers + promises. Microtasks can run before the browser paints, affecting perceived UI responsiveness 🧩 • Node.js: heavy microtask chains (Promise loops) can starve timers/I/O and make services jittery under load 🚦 • Debugging async: if something “runs too early,” look for a microtask sneaking in. Takeaway: use timers for yielding to the event loop; use microtasks for immediate async sequencing. 🔍 #javascript #nodejs #reactjs #frontend #webperformance #backendengineering
JavaScript Event Loop: Macrotasks vs Microtasks
More Relevant Posts
-
🌐 Day 62/100 — JavaScript Closures (the magic of remembering) Ever wondered how some functions "remember" values even after they finish running? That’s a closure. In simple words: A function can carry its outer variables with it — like a backpack — wherever it goes. Example: function counter() { let count = 0; return function () { count++; console.log(count); }; } const increment = counter(); increment(); // 1 increment(); // 2 increment(); // 3 Even though counter() already executed… count is still alive inside increment(). That’s closure memory. 💡 Why real websites use closures: • Data privacy (hide variables from global scope) • Event handlers remembering values • Caching & performance optimization • React hooks & state management So closures aren’t just theory — they power interactive UIs every day. Today’s takeaway: 👉 Functions in JavaScript don’t just run… they remember. #JavaScript #WebDevelopment #Frontend #100DaysOfCode #LearningInPublic
To view or add a comment, sign in
-
-
Day 6: Understanding State in React If Props allow components to receive data, then State allows components to manage and update their own data. 📌 What is State in React? State is a built-in object that allows a component to store data that can change over time. When the state changes, React automatically re-renders the component, updating the UI. 📌 Example using useState Hook import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>{count}</h1> <button onClick={() => setCount(count + 1)}> Increase </button> </div> ); } 📌 What is happening here? • count → current state value • setCount → function used to update the state • useState(0) → initial value of state When the button is clicked, the state updates and the UI re-renders automatically. 📌 Props vs State Props • Passed from parent component • Read-only State • Managed inside the component • Can be updated 📌 Why State is important State allows React applications to be interactive. Examples: • Counter apps • Form inputs • Toggle buttons • Dynamic UI updates #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingJourney #LearnInPublic
To view or add a comment, sign in
-
0ms doesn't always mean "now." Understanding JavaScript's hidden priority queue. If you’ve ever used setTimeout(() => {}, 0) to fix a bug, you’ve touched the Event Loop. But for "knowing it works" isn't enough. You need to know why. The Problem: Synchronous "Traffic Jams." JavaScript is single-threaded. If you run a massive for-loop to process 10,000 data points, the browser cannot paint, cannot scroll, and cannot respond to clicks. The app "freezes." The Real-Life Scenario: You’re fetching a massive list of users and need to filter them. If you do this filtering synchronously on the main thread, your "Loading..." spinner will actually stop spinning. The Solution: Task Splitting & Microtasks. 1. Microtasks (Promises/queueMicrotask): These have the highest priority. The browser will drain the entire microtask queue before moving on to anything else. 2. Macrotasks (setTimeout/setInterval): These are lower priority. The browser executes one task, then checks if it needs to re-render the UI. The Trade-off: The "Starvation" Risk. If you recursively call a Microtask, you can "starve" the event loop. Because microtasks always run before the next render, a runaway Promise chain will keep the UI frozen forever. A Macrotask (setTimeout), however, gives the browser a "breather" to paint the screen between tasks. Tip: Use Web Workers for heavy computation, but for UI-related logic splitting, understand your queues. #JavaScript #EventLoop #FrontendArchitecture #ProgrammingTips #SoftwareEngineering #WebDevelopment
To view or add a comment, sign in
-
Most JavaScript “magic” is just the prototype chain doing its job. 🧠🔍 When you access obj.foo, the engine doesn’t only check obj. It walks: obj → obj.__proto__ → … until it finds foo or hits null. That lookup is why “inheritance” in JS is really delegation. A few internals worth remembering: • Property reads traverse the chain; writes don’t. obj.foo = 1 creates/overwrites an own property, even if foo exists on the prototype. ✍️ • Methods on prototypes share one function instance across many objects (memory win vs per-instance methods). ⚙️ • Shadowing is a common perf + debugging trap: a hot path accidentally creates own props and changes shapes/hidden classes. 🧩 • Object.create(null) gives you a truly “dictionary” object with no inherited keys—useful for maps and security-sensitive parsing. 🔒 Real-world payoff: In React/Next.js apps and Node.js services, understanding prototype lookup helps you debug “why is this method missing?”, avoid prototype pollution pitfalls, and reason about perf in high-throughput APIs. 🚀 Next time a bug feels spooky, inspect the chain. 🕵️ #javascript #nodejs #frontend #webperformance #security
To view or add a comment, sign in
-
-
💡 Understanding window and this in JavaScript If you’re working in the browser, you’ve probably seen both window and this. They’re related — but not always the same. 🌐 What is window? window is the global object in the browser. It contains global variables, functions, and browser APIs like alert, setTimeout, and document. console.log(window.document); console.log(window.alert); Even global variables become part of window: var name = "Jim"; console.log(window.name); // Jim 🔑 What is this? this is a keyword whose value depends on how a function is called. In the global scope (browser): console.log(this === window); // true Inside a normal function (non-strict mode): function show() { console.log(this); } show(); // window Inside an object: const user = { name: "Jim", greet() { console.log(this.name); } }; user.greet(); // Jim ⚡ Key Difference • window → Always refers to the global browser object • this → Depends on the calling context 👉 Sometimes this === window, but not always. Understanding this difference is key to mastering JavaScript execution context. #JavaScript #Frontend #WebDevelopment #Programming
To view or add a comment, sign in
-
🚀 React Insight: Why key Matters in Lists If you’ve worked with lists in React, you’ve probably written something like this: {items.map((item) => ( <li key={item.id}>{item.name}</li> ))} But have you ever wondered why the key prop is so important? 🤔 React uses keys to identify which items in a list have: • changed • been added • been removed This helps React update the UI efficiently without re-rendering everything. ⚠️ What happens without proper keys? ❌ Components may re-render unnecessarily ❌ Component state can attach to the wrong item ❌ Performance issues in large lists 💡 Best Practices ✔️ Use a unique and stable identifier from your data (like id or uuid) => Bad practice: key={index} => Better approach: key={user.id} Using the array index as a key can cause bugs when the list reorders, adds, or removes items. ✨ Takeaway Keys aren’t just there to remove React warnings — they help React’s reconciliation algorithm update the DOM efficiently. Small detail. Big difference. #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
⚡ 1-Minute JavaScript Sometimes you want a function to run only once — no matter how many times it's called. Perfect for things like SDK initialization, configuration loading, or event setup. Utility function :- const once = (fn) => { let called = false; let result; return (...args) => { if (!called) { called = true; result = fn(...args); } return result; }; }; Usage :- const initAnalytics = once(() => { console.log("Analytics initialized"); }); initAnalytics(); // runs initAnalytics(); // ignored initAnalytics(); // ignored 🔍 Why this pattern is useful: 🛑 Prevents duplicate initialization ⚡ Avoids unnecessary computations 🧠 Encapsulates state cleanly inside a closure 🧩 Great for libraries, SDKs, and setup logic Small utility. Surprisingly powerful. #JavaScript #FrontendDevelopment #CleanCode #WebDevelopment #DevTips
To view or add a comment, sign in
-
-
If you work with JavaScript long enough, you’ll eventually run into situations where a function gets called way too many times. Think about typing in a search bar, scrolling a page, or resizing a browser window. These events fire continuously, and if we trigger heavy logic every single time, the app can become slow pretty quickly. This is where debouncing and throttling come in. Debouncing waits for the user to finish doing something before running the function. A simple example is a search bar. Imagine an API call running on every keystroke while someone types “javascript”. That’s 10 API calls when we really only need one. With debouncing, the function runs only after the user stops typing for a short delay. So instead of triggering the search repeatedly, it waits until the typing pauses. Throttling works a little differently. It makes sure a function runs at most once in a fixed time interval, no matter how many times the event fires. Scrolling is a good example. When a user scrolls, the event can fire dozens of times per second. Throttling limits how often the logic runs, like once every 200ms, which keeps the UI responsive without overwhelming the browser. In simple terms: Debounce → run after the activity stops Throttle → run at regular intervals during the activity Both are small techniques, but they make a big difference when it comes to performance and user experience. #javascript #webdevelopment #frontenddevelopment #fullstackdeveloper #reactjs #devcommunity #programming
To view or add a comment, sign in
-
-
You built a React component. Now how does it actually respond to the real world? Events. Re-renders. useEffect. These 3 connect everything together. 👆 Events — onClick, onChange, onSubmit (always camelCase, always a function reference) 🔁 Re-rendering — only state via setter triggers screen updates (regular variables won't!) ⚡ The Flow — click → setState → re-render → diff → DOM update 🎯 useEffect — run side effects like data fetching, timers, subscriptions 📋 Dependency Array — [] runs once, [count] runs when count changes, no array runs every time 🚀 Real pattern — loading state + useEffect fetch + dependency array The biggest beginner mistake? Using let count = 0 instead of useState(0) and wondering why the screen never updates. Save this. You'll come back to it. ♻️ Repost to help someone learning React. #React #useEffect #JavaScript #WebDevelopment #Frontend #LearnToCode
To view or add a comment, sign in
-
-
You've read the threads. You've seen the comparisons. You've nodded along to "React has problems" posts for years. Now do something about it. Open your terminal. Run this: npm create @granularjs/app my-super-app That's it. No config files to set up. No boilerplate to copy-paste. No 15-minute YouTube tutorial required. In under 30 seconds, you'll have a fully working app with: - Reactive state that updates the DOM directly — no virtual DOM, no diffing, no reconciliation - No re-renders — ever. Change a value, only the DOM nodes that use it update - No JSX, no TSX — plain JavaScript that does exactly what it says - Built-in router, SSR, query client, forms, WebSockets, virtual lists — batteries included - Global stores with one line: just export a reactive value from any file No useEffect. No useMemo. No useCallback. No dependency arrays. No stale closures. No race conditions between renders. The entire reactive model works outside of component lifecycles. State is a first-class primitive, not something bolted onto a rendering engine. You don't need to migrate anything. You don't need to convince your team. You don't need permission. Just run the command. Explore the code. Form your own opinion. If React is really fine, 30 seconds won't change your mind. But if it isn't — you just found the alternative. npm create @granularjs/app my-super-app Granular is open source: https://lnkd.in/dZGxj8Dy #javascript #frontend #webdev #opensource #reactivity
To view or add a comment, sign in
-
More from this author
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development