JavaScript Event Loop (Microtask vs Macrotask) — explanation We often see this code: console.log("start") setTimeout(() => { console.log("timeout") }, 0) Promise.resolve().then(() => { console.log("promise") }) console.log("end") Output: start end promise timeout Why does this happen? Basic: JavaScript is single-threaded That means it runs one thing at a time (Call Stack) But async tasks like setTimeout and Promise go to different queues. There are two types of queues: Microtask Queue (high priority) Promise.then() async/await Macrotask Queue (low priority) setTimeout setInterval DOM events Event Loop rule (very important): First, all synchronous code runs Then, all microtasks run Then, one macrotask runs Then the loop continues Easy way to remember: Sync → Microtask → Macrotask → Repeat Example breakdown: console.log("start") // sync setTimeout(() => { console.log("timeout") // macrotask }, 0) Promise.resolve().then(() => { console.log("promise") // microtask }) console.log("end") // sync Step by step: start → prints end → prints promise → runs next (microtask, higher priority) timeout → runs last (macrotask) Common mistake: Many people think: “setTimeout with 0ms runs immediately” This is wrong It only goes to the queue, it does not run immediately Final takeaway: JavaScript runs synchronous code first Then microtasks (Promise) Then macrotasks (setTimeout) Pro tip: If you understand this concept well, it will help you with: API handling React state updates Debugging async issues
JavaScript Event Loop: Microtask vs Macrotask Explained
More Relevant Posts
-
𝗗𝗲𝘀𝗶𝗴𝗻𝗶𝗻𝗴 𝗖𝘂𝘀𝘁𝗼𝗺 𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽 𝗜𝗺𝗽𝗹𝗲𝗺𝗲𝗻𝘁𝗮𝘁𝗶𝗼𝗻𝘀 𝗜𝗻 𝗝𝗦 You want to create custom event loop implementations in JavaScript. Here's what you need to know: - JavaScript is single-threaded, but it can handle asynchronous operations using the event loop. - The event loop manages a call stack, an event queue, and a callback queue. - You can create a custom event loop by grasping the standard event loop operation and reengineering aspects based on specific application needs. To design a custom event loop, consider the following: - Call Stack: manages the current execution context of functions - Task Queue: houses events/tasks that need to be executed after the stack is empty - Microtask Queue: contains promises or tasks scheduled via queueMicrotask Here's a basic example of a custom event loop in JavaScript: ``` is not allowed, instead use plain text class CustomEventLoop { constructor() { this.callStack = []; this.taskQueue = []; this.microtaskQueue = []; } run() { while (this.callStack.length > 0 || this.taskQueue.length > 0 || this.microtaskQueue.length > 0) { // execute microtasks first while (this.microtaskQueue.length > 0) { const microtask = this.microtaskQueue.shift(); this.callStack.push(microtask); microtask(); this.callStack.pop(); } // execute tasks from the task queue while (this.taskQueue.length > 0) { const task = this.taskQueue.shift(); this.callStack.push(task); task(); this.callStack.pop(); } } } enqueueMicrotask(microtask) { this.microtaskQueue.push(microtask); } enqueueTask(task) { this.taskQueue.push(task); } } ``` is not allowed, instead use plain text You can enhance this implementation by incorporating error handling mechanisms and considering concurrency nuances. Source: https://lnkd.in/gnPQzJmi
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Unlocking JavaScript with Proxy and Reflect API Explore the powerful Proxy and Reflect APIs in JavaScript that can elevate your coding skills. #javascript #proxy #reflect #webdevelopment ────────────────────────────── Core Concept Have you ever wished you could intercept and customize operations on objects in JavaScript? The Proxy and Reflect APIs allow you to do just that, making your code more flexible and powerful. Key Rules • Use Proxy to define custom behavior for fundamental operations (e.g., property lookup, assignment). • Reflect provides methods for interceptable JavaScript operations, acting as a companion to Proxy. • Remember to keep your use cases clear; these tools can add complexity if not applied thoughtfully. 💡 Try This const target = {}; const handler = { get: (obj, prop) => prop in obj ? obj[prop] : 'Property not found!' }; const proxy = new Proxy(target, handler); console.log(proxy.someProperty); ❓ Quick Quiz Q: What does the Proxy API allow you to do? A: Intercept and customize operations on objects. 🔑 Key Takeaway Embrace Proxy and Reflect to enhance your JavaScript code's functionality and behavior!
To view or add a comment, sign in
-
Small JavaScript bugs keep escaping to production and breaking critical user flows. Debugging inconsistent runtime behavior steals time from feature delivery. ────────────────────────────── Unlocking the Power of Proxy and Reflect in JavaScript Let's dive into the Proxy and Reflect APIs in JavaScript and how they can enhance your coding skills. #javascript #proxy #reflect #webdevelopment ────────────────────────────── Core Concept Have you ever wished you could intercept and customize operations on objects? The Proxy and Reflect APIs might be just what you need! They allow you to define custom behavior for fundamental operations (like property lookup and assignment) on objects. Are you ready to explore how they work? Key Rules • Proxies can intercept operations on objects (e.g., get, set). • Reflect provides methods to operate on objects directly, making it easier to manipulate them. • Both tools enable more dynamic and robust code, reducing boilerplate. 💡 Try This const target = { name: 'Alice' }; const handler = { get: (obj, prop) => Hello, ${obj[prop]}! }; const proxy = new Proxy(target, handler); console.log(proxy.name); // Outputs: Hello, Alice! ❓ Quick Quiz Q: What is the primary purpose of using a Proxy in JavaScript? A: To define custom behavior for fundamental operations on objects. 🔑 Key Takeaway Leverage Proxy and Reflect to write cleaner, more powerful JavaScript code!
To view or add a comment, sign in
-
🚀 JavaScript Event Loop Explained (Step-by-Step) JavaScript is single-threaded, meaning it executes one task at a time. So how does it handle asynchronous operations like Promises and setTimeout? Let’s break it down in a simple way: 🔹 Step 1: Synchronous Code (Call Stack) All synchronous code runs first in the Call Stack. Example: console.log("Hello") → executes immediately 🔹 Step 2: Promises (Microtask Queue) When a Promise resolves, its ".then()" callback is added to the Microtask Queue. This queue has higher priority than others. 🔹 Step 3: setTimeout (Callback Queue) setTimeout is handled by Web APIs and, after the timer completes, its callback moves to the Callback Queue. 🔹 Step 4: Event Loop The Event Loop continuously checks: • Is the Call Stack empty? • If yes, execute tasks from queues ⚡ Key Rule: Microtask Queue (Promises) executes before Callback Queue (setTimeout) 💡 Example: console.log("Hello"); Promise.resolve().then(() => console.log("Promise")); setTimeout(() => console.log("Callback"), 0); 📌 Output: Hello Promise Callback Even with 0ms delay, setTimeout runs last because it waits in the Callback Queue. --- 🎯 Why this matters: • Better understanding of async behavior • Easier debugging • Stronger interview preparation 🔖 Save this for future reference #JavaScript #EventLoop #MERN #WebDevelopment #Frontend #NodeJS
To view or add a comment, sign in
-
-
JavaScript functions can be defined and used in several ways, each serving specific purposes such as handling asynchronous code, creating objects, or maintaining scope. Core Function Definitions: These are the primary ways to create a function in JavaScript: Function Declaration: The traditional method using the function keyword followed by a name. They are hoisted, meaning they can be called before they are defined in the code. Function Expression: Assigning a function to a variable. These are not hoisted and must be defined before use. Arrow Function (ES6+): A concise syntax using =>. They do not have their own this context, instead inheriting it from the parent scope. Anonymous Function: A function without a name, often used inside function expressions or as callbacks. Specialized Function Types: Immediately Invoked Function Expression (IIFE): A function that executes immediately after it is defined. It is commonly used to create a private scope. Async Function: Defined with the async keyword, these always return a Promise and allow the use of await for cleaner asynchronous code. Generator Function: Declared with function*, these can pause and resume execution using the yield keyword. Constructor Function: Used with the new keyword to create multiple objects with the same structure. Recursive Function: A function that calls itself until a specific condition (base case) is met. Functional Concepts: Callback Function: A function passed as an argument to another function to be executed later. Higher-Order Function: A function that either takes one or more functions as arguments or returns a function. Pure Function: A function that always returns the same output for the same input and has no side effects. #JavaScript #React #Angular
To view or add a comment, sign in
-
-
𝗧𝗵𝗲 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗘𝗻𝗴𝗶𝗻𝗲: 𝗨𝗻𝗱𝗲𝗿𝘀𝘁𝗮𝗻𝗱𝗶𝗻𝗴 𝗖𝗮𝗹𝗹 𝗦𝘁𝗮𝗰𝗸, 𝗘𝘅𝗲𝗰𝘂𝘁𝗶𝗼𝗻 𝗖𝗼𝗻𝘁𝗲𝘅𝘁, 𝗮𝗻𝗱 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 You write JavaScript code every day. But do you know what happens when your code runs? You call functions, declare variables, and sometimes see undefined where you don't expect it. The answer lies in three core JavaScript mechanisms: - the call stack - the execution context - hoisting Understanding these internals helps you fix weird bugs and improve your code quality. The call stack tracks where your code is running. It's like a stack of plates - you can only add or remove from the top. When a function is called, a new frame is added to the stack. When the function returns, that frame is removed. The execution context is how your code runs. It has three parts: - variable environment - lexical environment - this binding Every execution context goes through two phases: creation and execution. During creation, the engine sets up the variable object, scope chain, and this binding. It also hoists declarations - registers them in memory before executing any code. Hoisting is often misunderstood. It's not that JavaScript moves declarations to the top of the file. Instead, the engine scans for declarations and registers them in memory before executing any code. Function declarations are fully hoisted, while var declarations are hoisted but their assignments are not. Let and const declarations are also hoisted, but they're not initialized until their declaration is reached. Understanding the call stack, execution context, and hoisting helps you debug faster, improve performance, and explain complex concepts with confidence. It's not just theory - it has a direct impact on your daily work as a developer. Source: https://lnkd.in/gbPtAu5N
To view or add a comment, sign in
-
🔑 JavaScript Set Methods – Quick Guide 1. Creation const letters = new Set(["a","b","c"]); // from array const letters = new Set(); // empty letters.add("a"); // add values 2. Core Methods MethodPurposeExampleReturns add(value)Add unique valueletters.add("d")Updated Set delete(value)Remove valueletters.delete("a")Boolean clear()Remove all valuesletters.clear()Empty Set has(value)Check existenceletters.has("b")true/false sizeCount elementsletters.sizeNumber 3. Iteration Methods MethodPurposeExample forEach(callback)Run function for each valueletters.forEach(v => console.log(v)) values()Iterator of valuesfor (const v of letters.values()) {} keys()Same as values() (compatibility with Maps)letters.keys() entries()Iterator of [value, value] pairsletters.entries() 4. Key Notes Unique values only → duplicates ignored. Insertion order preserved. typeof set → "object". set instanceof Set → true. 📝 Exercise Answer Which method checks if a Set contains a specified value? 👉 Correct answer: has() 🎯 Memory Hooks Set = Unique Collection Think: “No duplicates, only distinct members.” add to insert, has to check, delete to remove, clear to reset.
To view or add a comment, sign in
-
Stop using `new CustomEvent()`. There is a much better way to handle events in JavaScript. 1. The old habit For years, we have used `CustomEvent` to pass data around. It works, but it has flaws. You have to wrap your data inside a detail property. It feels clunky and "unnatural" compared to other objects. 2. The problem with CustomEvent It creates friction in your code: - The syntax is verbose. - You cannot access your data directly (you always need .detail). - It is difficult to type correctly in TypeScript. 3. The modern solution You don't need `CustomEvent` anymore. You can simply create your own class and extend `Event`. It looks like this: class UserLoginEvent extends Event { ... } 4. Why is it better? Subclassing `Event` is the standard way now. It offers clear advantages: - It uses standard JavaScript class syntax. - Your data sits on the event itself, not inside .detail. - It is much easier to define types for your custom events. - It works in all modern browsers. 5. It is time to upgrade If you want cleaner, strictly typed events, try extending the native `Event` class. It makes your code easier to read and maintain. Do you still use `CustomEvent` or have you switched?
To view or add a comment, sign in
-
-
📌 JAVASCRIPT VS A.I AUTOMATION As a developer using JavaScript, this is in connecting with the scopes of JavaScript. The Scope of JavaScript refers to the visibility of variable and functions within a program of codes. Which are: 1. Global scope: this variable is visible anywhere in the javascript program. 2. Function scope: this is a variable created when a function is declared and it's variable and functions are only visible withing that function. A sample of it is: Function funName(){ var fs = "..." alert (fs); console.log(fs); } funName(); Now looking at this, A.I codes misinterprets the function scopes and genrate codes that carries just global scopes or even most times Interchange function scopes with global scopes when giving a variable function. 📌 The risk of this common error in our program will not appear at the beginning of the project but during debugging and code maintenance. Wonder why JavaScript bugs gives you sleepless nights? This is one of the main reasons. This is a call for developers and vibe coders to learn the intimate differences between GLOBAL SCOPE VARIABLES and FUNCION SCOPE VARIABLES. You A.I JavaScript code can cause you harm later if you do not learn this earlier. 📌 A.I. frequently misunderstands Hoisting and the Temporal Dead Zone (TDZ) when creating nested functions. It often defaults to legacy var logic within closure loops (because the bulk of the training data still uses it) rather than modern let or const for block scoping. It optimizes for visual syntax, not runtime safety. Automation without technical intuition creates technical debt. Want more daily strategy from the cutting edge of web infrastructure? connect with snow works #WorksTechnology #JavaScriptMastery #CodingArchitecture #AIPerformance #TechnicalIntuition #WebArchitecture #SoftwareDesign #WebDevStrategy
To view or add a comment, sign in
-
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
1. There is no event loop in JavaScript. Event Loop is a host environment artifact that exists only there, where you embed JavaScript, because JavaScript is a scripting language. It cannot exist without being embedded somewhere. So when you talk about "Event loop in JS" you probably mean Event Loop of some specific host environment like Browser or Node js. Your host environment can even run js runtime without event loop. 2. JavaScript is not single or multi threaded. Again, it's a scripting language so it needs to be embedded into some host. That host can provide an ability to run js runtime in multiple threads. The question is does JS specification give us anything to work with JS in multiple threads? Yes, it does. We have Atomics and SharedArrayBuffer which allow you to do some stuff it multiple threads.