Day 70 of me reading random and basic but important dev topicsss...... Today I revisited event loops..... At its core, the JS engine runs an endless loop: Wait for tasks -> Execute them -> Sleep. But how does it prioritize what to execute next? It comes down to two distinct queues: Macrotasks and Microtasks. 1. The Macrotask Queue (Tasks) When an external event occurs, the browser queues a macrotask. Examples include: • Executing a newly loaded <script> • Dispatching user events (e.g., mousemove, click) • Running a setTimeout / setInterval callback Tasks are processed "first come, first served." But here is the critical part: Rendering never happens while a task is executing. If a single macrotask takes too long, the browser can't process user inputs or paint to the DOM, eventually throwing a "Page Unresponsive" error. 2. The Microtask Queue Microtasks come strictly from our code. The most common sources are: • Promise handlers (.then, .catch, .finally) • await operations • Explicitly queued tasks via queueMicrotask(func) The Execution Order (The Golden Rule): 1. Dequeue and run the oldest Macrotask. 2. Execute ALL Microtasks. If a microtask creates another microtask, it gets executed in this same phase! 3. Render DOM changes (if any). 4. Wait for the next Macrotask and repeat. Microtasks run immediately after the current macrotask and before any UI rendering or network event handling. This guarantees that application state remains untouched between microtasks.... Keep Learning!!!!!! #JavaScript #WebDevelopment #SoftwareEngineering #FrontendDev #EventLoop
JS Event Loop: Macrotasks & Microtasks Explained
More Relevant Posts
-
🚀 Stop adding 100+ event listeners to your code! Ever built a long list or a dynamic dashboard and felt your code getting "heavy"? 🏋️♂️ If you're manually attaching a click listener to every single item, you're missing out on one of JavaScript’s most powerful patterns: Event Delegation. The Magic of Event Bubbling 🫧 In the DOM, events don't just stay where they happen. When you click a button, that event "bubbles" up like a bubble in water—from the button, to its parent, to the body, all the way to the root. The Solution: Event Delegation 🤝 Instead of giving a listener to every child, you give one listener to their parent. Why this wins: ✅ Memory Efficiency: One listener uses far less memory than 100. ✅ Dynamic Support: It automatically works for new items added later! ✅ Cleaner Code: Centralize your logic in one place. How are you optimizing your DOM interactions lately? Let's discuss below! 👇 #JavaScript #WebDevelopment #CodingTips #FrontendDev #CleanCode #SoftwareEngineering
To view or add a comment, sign in
-
Day 71 of me reading random and basic but important dev topicsss..... Yesterday I read about the theory behind Macrotasks and Microtasks. Today, I read the practical, architectural pattern: Splitting CPU-hungry tasks. Imagine you have a massive task - like syntax highlighting 100,000 lines of code or formatting a massive dataset. If you run this in a single standard function, the JS engine locks up. The DOM won't paint, and clicks are ignored. The Solution: Chunking with setTimeout We can unblock the UI by splitting the massive job into smaller macrotasks using zero-delay setTimeout. Instead of running a loop to 1,000,000,000 all at once: 1. Process the first 1,000,000 items. 2. Call setTimeout(chunk, 0) to schedule the next batch. 3. Return control to the Event Loop. Because we returned control, the engine can now process pending clicks, handle network responses, and crucially Render the DOM. Use-Case: Progress Indicators Because DOM updates only paint after the currently running task completes, a standard heavy for loop updating a div.innerHTML will only show the final 100% state. The user sees a frozen screen, then a jump to completion. By splitting the task via setTimeout, the browser gets a chance to render the intermediate states, allowing us to build buttery-smooth loading/progress bars purely in single-threaded JS.... Tip for Maximum Performance: When chunking, move your setTimeout scheduling to the beginning of your function block rather than the end. The browser enforces a minimum delay of ~4ms for nested setTimeouts. Scheduling it immediately means the browser starts counting that 4ms delay while your current chunk is executing, drastically reducing overall execution time! Keep Learning!!!! #JavaScript #Performance #SoftwareArchitecture #WebDev #Engineering
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗖𝗦𝗦 𝗢𝗻𝗹𝗬 𝗦𝗲𝗰𝗿𝗲𝘁 𝗠𝗲𝗻𝗨 You're back for Weekly Challenge #5. This one is sneaky and super satisfying when you get it right. You will build a CSS-only secret menu - a hidden UI easter egg that appears when the user does something specific. Your mission is to make a menu that starts invisible and shows up when the user triggers it in a clever way. Not a normal button, not a big link. Something subtle that makes people wonder how they opened it. Here are the rules: - No JavaScript - Menu must start fully hidden - User must perform a non-obvious action to reveal it - Menu must have at least 5 items - The reveal must be animated Your goal is to make it feel like a secret dev panel. A hidden door. A little "you found the easter egg" moment. You can also add a second hidden layer, a CSS-only lock/unlock toggle, or give it a theme. To enter, just drop your CodePen or GitHub link in the comments. Go make something sneaky. Source: https://lnkd.in/gtWR4Cki
To view or add a comment, sign in
-
Edit-State Reliability in Dynamic UI Components Worked on a fix for an issue where a saved value was not being shown correctly when reopening an edit modal across multiple line-item flows. The problem came from how the autocomplete field restored its initial value. It was trying to match only on the saved display text, which worked in some cases but failed when the returned option label format was different from the stored value. As a result, the data existed, but the field looked empty in the UI. To fix this, I updated the initialization logic so the autocomplete now restores the selected value by matching on a stable ID first, and only falls back to the display text if needed. I moved that logic into a shared helper and applied it across all affected directive paths to keep the behavior consistent. This change improved edit-state reliability and made the modal behave correctly across multiple transaction types. A solid example of how many UI bugs are really about making sure saved state maps back correctly to dynamically loaded component data. #SoftwareEngineering #Frontend #JavaScript #Debugging #EnterpriseSoftware #WebDevelopment #GitHub
To view or add a comment, sign in
-
-
𝐀𝐫𝐞 𝐲𝐨𝐮 𝐬𝐭𝐢𝐥𝐥 𝐥𝐞𝐭𝐭𝐢𝐧𝐠 `useEffect` 𝐫𝐞-𝐫𝐮𝐧 𝐲𝐨𝐮𝐫 𝐞𝐱𝐩𝐞𝐧𝐬𝐢𝐯𝐞 𝐥𝐨𝐠𝐢𝐜 𝐟𝐨𝐫 𝐧𝐨 𝐠𝐨𝐨𝐝 𝐫𝐞𝐚𝐬𝐨𝐧? 🤯 It’s a common scenario: you have a `useEffect` that sets up a subscription or an interval, and you really only want it to run once on mount and clean up on unmount. So you put an empty dependency array `[]`. But what happens when you need a reference to a mutable value (like a prop or state) inside that effect, but you don't want changes to that value to re-trigger the effect? If you add it to the dependency array, it re-runs. If you omit it, you risk stale closures. Enter `useRef` as your stable escape hatch! Instead of: ```typescript useEffect(() => { const handler = () => console.log(someProp); // someProp is stale window.addEventListener('scroll', handler); return () => window.removeEventListener('scroll', handler); }, []); // Empty deps, but `someProp` is captured at mount ``` Try this pattern: ```typescript const latestSomeProp = useRef(someProp); useEffect(() => { latestSomeProp.current = someProp; // Update the ref on every render const handler = () => console.log(latestSomeProp.current); // Always fresh! window.addEventListener('scroll', handler); return () => window.removeEventListener('scroll', handler); }, []); // Effect itself only runs once ``` This way, your `useEffect` only runs once for setup/teardown, but `latestSomeProp.current` always holds the most up-to-date value. It’s perfect for ensuring cleanup functions always operate on the current state or props, without re-triggering the effect. It's a subtle but powerful pattern for optimizing performance and avoiding tricky bugs in React. What other `useEffect` patterns have saved you from debugging hell? Share your tips! #React #FrontendDevelopment #JavaScript #WebDev #Performance
To view or add a comment, sign in
-
🚀 Simplifying API Calls in Redux with createAsyncThunk. Earlier, we had to write too much boilerplate for API calls in Redux. Handling: #loading #success #error …meant creating multiple action types, action creators, and reducers. Then I started using createAsyncThunk from Redux Toolkit 👇 It automatically generates: #pending #fulfilled #rejected So instead of writing everything manually, you just focus on the async logic. Example: export const fetchUsers = createAsyncThunk( "users/fetchUsers", async () => { const res = await fetch("https://lnkd.in/g27u5z_N"); return res.json(); } ); And handle states cleanly in extraReducers. 🔥 What I like about it: Reduces boilerplate significantly Makes async flow predictable Cleaner and more readable code 💬 What do you use for API calls in your projects? #React #Redux #Frontend #WebDevelopment #JavaScript #WebArchitecture #SoftwareEngineering
To view or add a comment, sign in
-
🚀 Understanding the JavaScript Event Loop (Microtasks vs Macrotasks) Consider this code: console.log("Start"); setTimeout(() => { console.log("Timeout"); }, 0); Promise.resolve().then(() => { console.log("Promise"); }); console.log("End"); What’s the output? Many expect: Start Timeout Promise End But actual output is: Start End Promise Timeout Why? Because of the Event Loop. JavaScript handles tasks in two major queues: • Microtasks (Promises, queueMicrotask) • Macrotasks (setTimeout, setInterval) Execution order: 1️⃣ Synchronous code runs first 2️⃣ Microtasks run next 3️⃣ Then Macrotasks Even if setTimeout has 0ms delay, it still waits for the macrotask queue. Understanding this explains: • Why some async bugs feel “random” • Why Promises run before setTimeout • Why UI updates sometimes behave unexpectedly JavaScript isn’t single-threaded chaos. It’s single-threaded with a well-defined event model. Understanding the Event Loop changes how you debug async code. What async behavior confused you the most before learning this? #javascript #frontenddeveloper #webdevelopment #eventloop #softwareengineering
To view or add a comment, sign in
-
-
🛠️ I've open-sourced my VS Code customization setup — and it's more than just a theme. After spending a lot of time fine-tuning my development environment, I packaged everything into a clean, reusable repository so others can benefit too. Here's what's inside: 📄 settings.json — My full VS Code settings, carefully configured for a clean and productive workflow 🎨 custom-vscode.css — Custom CSS to style the editor UI beyond what the default theme options allow ⌨️ vs-code-script.js — A custom command palette script to extend VS Code's built-in commands and speed up repetitive tasks Whether you're a developer looking to optimize your editor or just curious how far VS Code customization can go — this repo is for you. 💡 Your dev environment should work for you, not against you. 🔗 GitHub link in the comments — feel free to fork, star, or open a PR if you'd like to contribute! #VSCode #DeveloperTools #OpenSource #DevProductivity #WebDevelopment #CodingTips
To view or add a comment, sign in
-
-
I recently worked on a feature where I used URL parameters to display a specific product and track its delivery status on a separate page. In this video, I walked through how I implemented it from passing orderId and productId through the URL, to retrieving them on the tracking page and using them to render the correct product and delivery progress. This task pushed me to better understand: -How URL parameters work in real applications -Handling bugs like missing or incorrect parameters -Managing data flow between pages -Updating the UI dynamically based on real-time calculations (like delivery progress) It wasn’t just about getting it to work, but understanding why it works and fixing the issues that came up along the way. Still learning and improving every day 🚀 #JavaScript #FrontendDevelopment #WebDevelopment #LearningInPublic #BeginnerDeveloper
To view or add a comment, sign in
-
Why Front-end Bugs Are Often System Bugs. I recently fixed a bug where: • The header was perfectly styled • The footer looked completely broken Same page. Same CSS file. Same deployment. At first, it looked like a front-end issue. It wasn’t. It was a system issue. One invalid CSS block caused the browser to stop parsing the stylesheet. Everything after the error was silently ignored. That means: → The problem wasn’t spacing → The problem wasn’t colors → The problem wasn’t layout The problem was the system that delivered the UI. This changed how I think about engineering: I don’t just debug pages anymore. I debug pipelines, build outputs, parsers, and guardrails. Because in real systems: The UI is just the surface. The real system lives underneath. And sometimes the bug isn’t where you see it — it’s where the system stopped working. Curious: Have you ever chased a “front-end bug” that turned out to be something deeper? Hashtags #PlatformEngineering #DevSecOps #SoftwareEngineering #WebArchitecture #BuildInPublic
To view or add a comment, sign in
-
Explore related topics
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