🚀 JavaScript Simplified Series — Day 39 Yesterday we learned **Debounce**… 👉 Delay execution until user stops But what if you want something different? 🤔 👉 Run function at a **fixed interval** 👉 Even if user keeps triggering it This is where **Throttle** comes in 🔥 --- ## 🔥 Problem Imagine scrolling a page 😵 👉 Scroll event fires 100+ times per second 👉 Function runs again & again 👉 Performance drops 💥 --- ## 🔥 Solution → Throttle --- ## 🔹 What is Throttling? Throttling means: 👉 **Limit function execution** 👉 To once in a fixed time interval --- ## 🔹 Example ```javascript id="th1" function throttle(fn, delay) { let lastCall = 0 return function(...args) { let now = new Date().getTime() if (now - lastCall >= delay) { lastCall = now fn(...args) } } } ``` --- ## 🔹 Usage ```javascript id="th2" function handleScroll() { console.log("Scrolling...") } let throttledScroll = throttle(handleScroll, 1000) // call this on scroll event window.addEventListener("scroll", throttledScroll) ``` 👉 Runs only once every 1 second --- ## 🔍 Debounce vs Throttle 👉 Debounce → run after delay (last call) 👉 Throttle → run at intervals --- ## 🔥 Real Life Example Think of a **water tap 🚰** 👉 You open it → water flows continuously 👉 But flow is controlled 👉 That’s throttle --- ## 🔥 Where is Throttle used? 👉 Scroll events 👉 Resize events 👉 Button spam prevention 👉 Game loops --- ## 🔥 Simple Summary Throttle → limit execution Run → at fixed interval Improve → performance --- ### 💡 Programming Rule **Control how often your code runs. Performance matters.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototypes Day 35 → Classes Day 36 → Inheritance Day 37 → Modules Day 38 → Debounce Day 39 → Throttle Day 40 → Final JavaScript Wrap (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
Throttle JavaScript Function Execution for Improved Performance
More Relevant Posts
-
🚀 JavaScript Simplified Series — Day 24 You clicked a button… But something strange happened 😳 👉 Button ka event bhi chala 👉 Parent div ka event bhi chala 👉 Aur kabhi kabhi pura page react kar leta hai Why? 🤔 --- ## 🔥 This is called → Event Bubbling --- ## 🔹 Real Example ```html id="eb1" <div id="parent"> <button id="child">Click Me</button> </div> ``` ```javascript id="eb2" let parent = document.querySelector("#parent") let child = document.querySelector("#child") child.addEventListener("click", function() { console.log("Button Clicked") }) parent.addEventListener("click", function() { console.log("Div Clicked") }) ``` 👉 Output when button is clicked: Button Clicked Div Clicked --- ## 🔍 What’s happening? Event flow: 👉 First child (button) 👉 Then parent (div) 📌 Event travels **inside → outside** This is called **Event Bubbling** --- ## 🔹 Why does this happen? Because browser follows a flow: 👉 Target element → Parent → Body → Document --- ## 🔹 How to Stop Bubbling? Sometimes you don’t want parent event to trigger 😎 ```javascript id="eb3" child.addEventListener("click", function(e) { e.stopPropagation() console.log("Button Clicked") }) ``` 👉 Now only button event runs --- ## 🔥 Real Life Example Think of a **water bubble 🫧** Bubble upar jaati hai… 👉 Same way event travels upward --- ## 🔥 Simple Summary Event Bubbling → event moves upward Parent bhi trigger hota hai stopPropagation() → bubbling stop karta hai --- ### 💡 Programming Rule **Understand event flow warna bugs samajh nahi aayenge 😄** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 21 Yesterday we learned about DOM… But knowing DOM is not enough. 👉 You need to select elements first tabhi tum unhe change kar paoge 😎 🤔 Real Problem Socho tumhare paas ek website hai: <h1 id="title">Hello</h1> <p class="text">Welcome</p> <button>Click Me</button> Ab tum JavaScript se: 👉 h1 ka text change karna chahte ho 👉 button par click event lagana chahte ho But question is… 👉 Element milega kaise? 🔥 Solution → DOM Selectors JavaScript hume multiple ways deta hai elements select karne ke liye 🔹 1. getElementById() let heading = document.getElementById("title") console.log(heading) 📌 Select by id 👉 Fast & direct 🔹 2. getElementsByClassName() let text = document.getElementsByClassName("text") console.log(text) 📌 Returns HTMLCollection (multiple elements) 🔹 3. querySelector() (Most Important 🔥) let heading = document.querySelector("#title") 👉 Select by id (#) 👉 Select by class (.) 👉 Select by tag document.querySelector(".text") document.querySelector("button") 📌 Returns first matching element 🔹 4. querySelectorAll() let items = document.querySelectorAll(".text") console.log(items) 📌 Returns NodeList (all elements) 🔥 Real Life Example Think of DOM like a big room full of items 🏠 Selectors are like: 👉 Searching by name (id) 👉 Searching by group (class) 👉 Searching anything (querySelector) 🔥 Simple Summary getElementById → single element getElementsByClassName → multiple elements querySelector → first match querySelectorAll → all matches 💡 Programming Rule First select the element. Then control it. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
Most confusion around 𝘁𝗵𝗶𝘀 in JavaScript comes from one mistake: We focus on where the function is written instead of how it’s called. Here’s a simple breakdown 👇 🔗 https://lnkd.in/gaZCBkUe Chai Aur Code ☕ #javascript #programming #webdevelopment
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 30 JavaScript feels fast… But have you ever wondered 👇 👉 How does it handle multiple tasks at once? 👉 How does async code run without blocking? This is where the **Event Loop** comes in 😎 --- ## 🤯 The Big Confusion JavaScript is **single-threaded** 👉 It can do **one thing at a time** Then how does this work? 👇 ```javascript id="el1" console.log("Start") setTimeout(() => { console.log("Async Task") }, 0) console.log("End") ``` 👉 Output: Start End Async Task Wait… why? 🤔 --- ## 🔥 Behind the Scenes JavaScript has 3 main parts: 👉 Call Stack 👉 Web APIs 👉 Callback Queue --- ## 🔹 Step by Step Flow 1️⃣ `console.log("Start")` → runs first 2️⃣ `setTimeout` → goes to **Web API** 3️⃣ `console.log("End")` → runs next 4️⃣ Callback goes to **Queue** 5️⃣ Event Loop checks → stack empty? 6️⃣ Yes → push callback to stack 👉 Then runs → "Async Task" --- ## 🔍 Visualization ```id="viz1" Call Stack → Executes code Web APIs → Handles async tasks Queue → Stores callbacks Event Loop → Manages everything ``` --- ## 🔥 Real Life Example Think of a **restaurant 🍽️** 👉 Waiter takes order → sends to kitchen 👉 Kitchen prepares food 👉 Meanwhile waiter serves others 👉 When food is ready → serves you 👉 Event Loop = waiter managing tasks --- ## 🔥 Simple Summary JS → single-threaded Async → handled outside Event Loop → manages execution --- ### 💡 Programming Rule **JavaScript is not multi-threaded… but it behaves like it is.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 31 You wrote a variable… But suddenly 😳 👉 It works in one place 👉 But gives error in another Why? 🤔 --- ## 🔥 This is called → Scope --- ## 🔹 What is Scope? Scope defines **where a variable can be accessed** 👉 Kaha use kar sakte ho 👉 Kaha nahi --- ## 🔹 1. Global Scope ```javascript id="sc1" let name = "Abhay" function greet() { console.log(name) } greet() ``` 👉 Accessible everywhere 📌 Global = sab jagah access --- ## 🔹 2. Function Scope ```javascript id="sc2" function test() { let age = 22 console.log(age) } test() console.log(age) ❌ ``` 👉 Error ❌ 📌 Function ke bahar access nahi --- ## 🔹 3. Block Scope (let & const) ```javascript id="sc3" if (true) { let city = "Delhi" console.log(city) } console.log(city) ❌ ``` 👉 Error ❌ 📌 Block ke bahar access nahi --- ## 🔥 var vs let vs const ```javascript id="sc4" if (true) { var x = 10 } console.log(x) // works 😳 ``` 👉 `var` ignores block scope 📌 `let` & `const` follow block scope --- ## 🔥 Real Life Example Think of a house 🏠 👉 Global → pura ghar 👉 Function → ek room 👉 Block → ek drawer Har cheez har jagah access nahi hoti --- ## 🔥 Simple Summary Global → everywhere Function → inside function Block → inside {} --- ### 💡 Programming Rule **Keep variables limited. Smaller scope = fewer bugs.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 35 Prototypes are powerful… But let’s be honest 😅 👉 Syntax thoda confusing lagta hai 👉 Hard to read 👉 Not beginner friendly What if we could write the same thing in a **clean and simple way?** 🤔 --- ## 🔥 Solution → Classes --- ## 🔹 What are Classes? Classes are just a **clean syntax over prototypes** 👉 Same power 👉 Better readability --- ## 🔹 Without Class (Old Way) ```javascript id="clx1" function User(name) { this.name = name } User.prototype.greet = function() { console.log("Hello " + this.name) } let u1 = new User("Abhay") u1.greet() ``` --- ## 🔹 With Class (Modern Way 😎) ```javascript id="clx2" class User { constructor(name) { this.name = name } greet() { console.log("Hello " + this.name) } } let u1 = new User("Abhay") u1.greet() ``` 👉 Same result 👉 Cleaner code --- ## 🔹 Adding More Methods ```javascript id="clx3" class User { constructor(name) { this.name = name } greet() { console.log("Hello " + this.name) } sayBye() { console.log("Goodbye") } } ``` --- ## 🔥 Real Life Example Think of a **blueprint 🏗️** 👉 Class = blueprint 👉 Object = actual building Same design → multiple objects --- ## 🔥 Simple Summary Class → cleaner syntax Constructor → initialize values Methods → behavior --- ### 💡 Programming Rule **Write code that humans can read. Classes make code cleaner.** --- If you want to learn JavaScript in a **simple and practical way**, you can follow these YouTube channels: • Rohit Negi --- 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API Day 30 → Event Loop Day 31 → Scope Day 32 → Hoisting Day 33 → Closures Day 34 → Prototypes Day 35 → Classes Day 36 → Inheritance (Next Post) --- Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
-
🚀 JavaScript Simplified Series — Day 25 Imagine this 👇 You have a list of 100 items… And you want to add a click event on each item 😵 Will you do this? let items = document.querySelectorAll("li") items.forEach(item => { item.addEventListener("click", function() { console.log("Item clicked") }) }) Works… but not efficient ❌ 👉 What if new items are added later? 👉 You’ll have to add event again 😩 🔥 Solution → Event Delegation 🔹 Idea Instead of adding event to every child… 👉 Add event to parent And detect which child was clicked 🔹 Example <ul id="list"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> let list = document.querySelector("#list") list.addEventListener("click", function(e) { console.log(e.target.innerText) }) 👉 Click any item → it works 😎 🔍 How it works? Because of event bubbling 👉 Event child se parent tak travel karta hai Parent catches it 🔹 Why Event Delegation is Powerful? ✅ Less code ✅ Better performance ✅ Works for dynamic elements 🔥 Real Life Example Think of a classroom 🎓 Instead of asking each student individually… 👉 Teacher asks whole class Jo respond kare → identify karo 🔥 Simple Summary Event Delegation → parent handles child events Uses → event bubbling Benefit → efficient & scalable 💡 Programming Rule Don’t attach events everywhere. Use delegation smartly. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
-
🚀 **Understanding JavaScript Variables Like a Pro (var vs let vs const)** If you're working with JavaScript, choosing the right keyword — `var`, `let`, or `const` — is more important than you think. Here’s a simple breakdown 👇 🔸 **var** * Function scoped * Can be re-declared * Can be re-assigned * Hoisted with `undefined` 👉 Mostly avoided in modern JavaScript due to unexpected behavior. --- 🔹 **let** * Block scoped * Cannot be re-declared in same scope * Can be re-assigned * Hoisted but in Temporal Dead Zone (TDZ) 👉 Best for variables that will change. --- 🔒 **const** * Block scoped * Cannot be re-declared * Cannot be re-assigned * Must be initialized at declaration 👉 Best for constants and safer code. --- 💡 **Pro Tip:** Always prefer `const` by default → use `let` when needed → avoid `var`. --- 📊 The attached diagram explains: * Scope hierarchy (Global → Function → Block) * Memory behavior * Key differences visually --- 🔥 Mastering these fundamentals helps you: ✔ Write cleaner code ✔ Avoid bugs ✔ Crack interviews easily --- #JavaScript #WebDevelopment #Frontend #Coding #Programming #Developers #LearnToCode #Tech #SoftwareEngineering #NodeJs #Json
To view or add a comment, sign in
-
-
🔥 var vs let vs const in JavaScript (Explained Simply) Understanding the difference between `var`, `let`, and `const` is essential for writing clean and bug-free JavaScript code. Let’s break it down 👇 🔹 1️⃣ var #Example var name = "Amit"; var name = "Rahul"; // Re-declaration allowed ✅ Function scoped ✅ Can be re-declared and updated ⚠️ Hoisted with `undefined` ❌ Can cause unexpected bugs 👉 Avoid using `var` in modern JavaScript. 🔹 2️⃣ let #Example let age = 25; age = 30; // Update allowed ✅ Block scoped ❌ Cannot be re-declared in same scope ✅ Can be updated ✅ Safer than `var` 👉 Use `let` when the value needs to change. 🔹 3️⃣ const #Example const pi = 3.14; // pi = 3.1415; ❌ Error ✅ Block scoped ❌ Cannot be re-declared ❌ Cannot be updated ✅ Must initialize at declaration 💡 For objects/arrays → You can modify properties, but not reassign the reference. 🚀 Best Practice ✔️ Use `const` by default ✔️ Use `let` when reassignment is required ❌ Avoid `var` Writing cleaner code starts with choosing the right variable declaration. #JavaScript #WebDevelopment #Frontend #Programming #CodingTips #Developers
To view or add a comment, sign in
-
-
Ever wondered what actually happens when you use new in JavaScript? 🤔 Today I learned: 👉 How objects are created behind the scenes 👉 How prototypes are linked 👉 How constructors build instances Documented everything in this article 👇 https://lnkd.in/gr2UykHg #JavaScript #100DaysOfCode #WebDev #chaicode Chai Code Hitesh ChoudharyPiyush Garg Akash Kadlag Suraj Kumar Jha
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