Theory: "setTimeout callbacks execute after the Call Stack is empty." Practice: I'd never actually put numbers to it until today. ```javascript const start = Date.now(); const delay = (label, ms) => console.log(`${label} delayed by ${Date.now() - start - ms}ms`); setTimeout(delay, 0, '0ms', 0); setTimeout(delay, 1, '1ms', 1); setTimeout(delay, 100, '100ms', 100); setTimeout(delay, 300, '300ms', 300); setTimeout(delay, 600, '600ms', 600); for (let i = 0; i < 100000000; i++); // ~100ms blocking work ``` Output: ``` 0ms → delayed by 103ms 1ms → delayed by 102ms 100ms → delayed by 3ms 300ms → delayed by 2ms 600ms → delayed by 1ms ``` → 0ms and 1ms were ready instantly, but blocked by the loop → 100ms fired right as the stack cleared → 300ms and 600ms had almost zero extra delay (That ~1-2ms you see even on 300ms/600ms? That's just Event Loop & system overhead — unavoidable.) I've known how the Event Loop works for years. But seeing the actual pattern in milliseconds — that was oddly satisfying. There's a difference between knowing something and feeling it click at a deeper level. #JavaScript #EventLoop #AsyncProgramming
setTimeout callbacks execute after Call Stack empties
More Relevant Posts
-
JavaScript Tricky question The output is: 1 → 5 → 3 → 4 Here's why, step by step: 1 — test() is called. Execution enters the try block synchronously and console.log("1") runs immediately. 5 — await Promise.reject("Error") is hit. await suspends the async function and hands control back to the call stack. So test() pauses and console.log("5") — which is outside and synchronous — runs next. 3 — The microtask queue resumes. The rejected promise is caught by the catch block, so console.log("3") runs. "2" is never reached because the line after await is skipped on rejection. 4 — finally always runs, regardless of success or failure, so console.log("4") runs last. The core rule to internalize: await doesn't block the thread — it only pauses that async function. Everything synchronous after the test() call runs first, then the microtask queue drains once the call stack is empty.
To view or add a comment, sign in
-
-
𝗧𝗵𝗶𝘀 𝗜𝘀 𝗔𝗿𝗿𝗮𝘆 𝗗𝗲𝘀𝘁𝗿𝘂𝗰𝘁𝘂𝗿𝗶𝗻𝗴 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 You write JavaScript code and think: "Why so many lines to grab array values?" You start with a simple array: array[0], array[1], array[2]. Then you wonder: Is JavaScript really this repetitive? Good news: you are missing something - it's called Array Destructuring. Array destructuring is an ES6 feature that extracts values from an array and assigns them to variables in one line. It's like unpacking a suitcase: instead of pulling out clothes one by one, you unpack everything at once. Example: const numbers = [10, 20, 30]; const [a, b, c] = numbers; console.log(a, b, c); Output:
To view or add a comment, sign in
-
𝗛𝗮𝗻𝗱𝗹𝗲 𝗘𝗿𝗿𝗼𝗿𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗣𝗿𝗼 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 What is an error? An error is a mistake that disrupts the normal flow of a program. Errors occur due to incorrect syntax or logical mistakes in the code. You can handle runtime errors in JavaScript using a try-catch block. The try block contains the code that may introduce errors. If an error occurs, execution jumps to the catch block. The catch block has access to the error object, which contains the error name and message. Here's an example: ``` is not allowed. Here is the corrected version: try { let user = null; console.log(user.name); } catch (error) { console.log("Error caught:", error.message); } finally { console.log("Execution completed"); } Try-catch blocks won't catch errors in asynchronous callbacks unless the try-catch code is inside the callback function. You must put try-catch inside async callbacks. Error objects have core properties: - name: the type of error - message: a human-readable string - stack: the trace of function calls You can throw user-defined exceptions using the throw statement. Example: function withdraw(amount, balance){ if (amount > balance) { throw new Error("Insufficient balance"); } return balance - amount; } try { withdraw(500, 100); } catch (err) { console.log(err.message); } Source: https://lnkd.in/g4eneE3Y
To view or add a comment, sign in
-
📊 Day 13 – Poll Answer & Explanation ```javascript const a = [1, 2, 3]; const b = a; b.push(4); console.log(a); console.log(b); ``` ### ❓ What will be the output? ## ✅ Correct Answer: **B** ``` [1,2,3,4] [1,2,3,4] ``` --- ## 📌 Step-by-Step Explanation **1️⃣ Arrays are Reference Types** In **JavaScript**, arrays are **objects**. Objects are stored in **memory by reference**, not by value. --- **2️⃣ Assigning `b = a`** ```javascript const b = a; ``` This **does NOT create a new array**. Instead, **both `a` and `b` point to the same array in memory**. ``` a ──► [1,2,3] b ──► ``` --- **3️⃣ Modifying the Array** ```javascript b.push(4); ``` Since **`b` references the same array**, the original array is modified. ``` a ──► [1,2,3,4] b ──► ``` --- **4️⃣ Final Output** ```javascript console.log(a); // [1,2,3,4] console.log(b); // [1,2,3,4] ``` Both variables print the **same updated array**. --- ## 💡 Key Takeaway 👉 **Arrays and objects in JavaScript are stored by reference.** 👉 If multiple variables reference the **same object**, modifying one **affects all of them**. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #CodingInterview #DeveloperCommunity #100DaysOfCode #LearnToCode
To view or add a comment, sign in
-
𝗛𝗮𝗻𝗱𝗹𝗲 𝗘𝗿𝗿𝗼𝗿𝘀 𝗟𝗶𝗸𝗲 𝗔 𝗣𝗿𝗼 𝗜𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 What is an error? An error is a mistake that disrupts a program's normal flow and prevents the code from executing properly. Errors occur due to incorrect syntax or logical mistakes in the code. You can handle runtime errors in JavaScript using a try-catch block. The try block contains code that may introduce errors. If an error occurs, execution jumps to the catch block. The catch block runs only when an error occurs in the try block and has access to the error object. Here's how it works: - Try block: contains code that may cause an error - Catch block: runs if an error occurs and has access to the error object - Finally block: always runs after try and catch, usually used for cleanup For example: ``` try { let user = null; console.log(user.name); // Error } catch (error) { console.log("Error caught:", error.message); } finally { console.log("Execution completed"); } ``` Note that try-catch blocks won't catch errors in asynchronous callbacks unless the try-catch code is inside the callback function. You must put try-catch inside async callbacks. Error objects have core properties: - name: specifies the type of error - message: a human-readable string for custom error messages - stack: provides the trace of function calls, including line numbers You can throw user-defined exceptions using the throw statement. Built-in error types include TypeError and ReferenceError. Source: https://lnkd.in/g4eneE3Y
To view or add a comment, sign in
-
📊 Day 14 – Poll Answer & Explanation console.log([1,2] + [3,4]); ❓ What will be the output? Many developers expect array concatenation, but JavaScript behaves differently ✅ Step-by-Step Explanation Step 1️⃣ JavaScript sees the `+` operator. The `+` operator can perform: Addition String concatenation Step 2️⃣ When arrays are used with `+`, JavaScript converts them to strings. [1,2].toString() // "1,2" [3,4].toString() // "3,4" Step 3️⃣ Now the operation becomes: "1,2" + "3,4" Step 4️⃣ This performs string concatenation. "1,23,4" ### 🎯 Final Output 1,23,4 📌 Key Concept The `+` operator with arrays converts them into strings first, then performs string concatenation. #JavaScript #WebDevelopment #FrontendDevelopment #Programming #CodingInterview #DeveloperCommunity #100DaysOfCode #LearnToCode
To view or add a comment, sign in
-
Quick tech tip of the day (Webflow edition). If you have a blog article page with a ToC block on it that has internal scrolling, and you want to make it automatic with your page content scroll - here’s a quick JavaScript solution: // Script START <script> document.addEventListener('DOMContentLoaded', function () { const toc = document.querySelector('.blog_toc-inner'); if (!toc) return; const observer = new MutationObserver(() => { const activeLink = toc.querySelector('.w--current'); if (activeLink) { toc.scrollTo({ top: activeLink.offsetTop - toc.clientHeight / 2 + activeLink.clientHeight / 2, behavior: 'smooth' }); } }); observer.observe(toc, { subtree: true, attributeFilter: ['class'], attributes: true }); }); </script> // Script END Works perfectly with Finsweet library, and even Locomotive scroll by LENIS. Enjoy! ✌ #DevTips #Webflow #JavaScript #CodeSolution #WebDevelopment
To view or add a comment, sign in
-
-
JavaScript closures are one of those concepts that seem confusing at first but are incredibly powerful. At a basic level, a closure allows a function to remember variables from its outer scope, even after that scope has finished executing. Understanding this makes patterns like callbacks and hooks much clearer. Source: MDN Web Docs – Closures https://lnkd.in/gZsRizzt
To view or add a comment, sign in
-
Closures are a JavaScript Superpower, but are you leaking memory with them? 🛑 We all love closures for data encapsulation and creating stateful functions. But with great power comes the responsibility of understanding the retained reference problem. A closure can inadvertently keep large objects, such as massive arrays or DOM elements, in memory long after you've finished with them. If your closure is still reachable (e.g., in an interval, an event listener, or a global variable), the Garbage Collector (GC) is stuck. It can't free the memory. This is a subtle memory leak that can degrade performance over time. The key to fixing it is breaking the reference chain. I've created a two-part diagram to visualize exactly how it happens and, more importantly, how to fix it with simple practices. Here are the essential steps for prevention: 1. Be Intentional about Capture: Redesign your closures to avoid holding onto unnecessary, large objects. 2. Explicit Cleanup: Set closure-related variables to null once they are no longer needed. 3. Proper Tear-Down: Always use clearInterval(), clearTimeout(), and removeEventListener() in your cleanup phases. Check out the illustration for a visual walkthrough! 👇
To view or add a comment, sign in
-
-
JavaScript Subtleties So, this code looks like it is trying to convert an object to an array, when in fact it is creating an object whose values are arrays! const events= {}; functionon(event, handler) { if (!events[event]) { events[event] = []; } events[event].push(handler); }
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