Throttle is like putting a speed limit on function execution. Resize a window without throttle? Your function fires hundreds of times per second. With throttle? Maximum once every 300ms, no matter how fast you resize. ``` function throttle(fn, delay = 300) { let flag = true; return function(...args) { if (!flag) return; // Still in cooldown fn.apply(this, args); flag = false; setTimeout(() => flag = true, delay); }; } ``` How it works: Execute once, then enter cooldown. All calls during cooldown are ignored. After the delay, function can execute again. Common use cases: 1. Window resize events 2. Scroll events 3. Button clicks (prevent spam) 4. Mouse movement tracking Throttle vs Debounce: 1. Debounce: waits until you stop 2. Throttle: executes at regular intervals while you continue Full implementation with examples: https://lnkd.in/dG7nwKXh Thanks to Akshay Saini 🚀 for the explanation. Where do you use throttling? Let me know if I missed anything - happy to improve it. #JavaScript #WebDev #Coding #LearningInPublic #100DaysOfCode
Throttle Function Execution with JavaScript
More Relevant Posts
-
Debounce and throttle solve different problems. Most people use the wrong one. Debounce: Waits until you stop, then executes once Throttle: Executes at regular intervals while you continue Think of it like: 1. Debounce = elevator door (waits for people to stop entering) 2. Throttle = traffic light (lets cars through at fixed intervals) ``` // Search input - wait until done typing let debouncedSearch = debounce(searchAPI, 300); // Scroll handler - update while scrolling let throttledScroll = throttle(updatePosition, 100); ``` Quick decision: 1. Want it to run WHILE the event happens? → Throttle 2. Want it to run AFTER the event stops? → Debounce Common mistake: using debounce for scroll events. Your UI won't update until scrolling stops. Use throttle instead - it updates periodically while you scroll. Full comparison with implementations: https://lnkd.in/dN7B7TQN Thanks to Akshay Saini 🚀 for the clear breakdown. Which one do you confuse more often? Let me know if I missed anything - happy to improve it. #JavaScript #WebDev #Coding #LearningInPublic #100DaysOfCode
To view or add a comment, sign in
-
🚀 𝗡𝗲𝘄 𝗣𝗥 𝗠𝗲𝗿𝗴𝗲𝗱 I recently tackled a fun logical puzzle: how to move all zeroes to the end of an array while maintaining the relative order of the non-zero elements. This challenge, which I've documented in my latest PR (https://lnkd.in/dSXWnSES), really tested my ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 to array manipulation. My solution involved iterating through the array and using a pointer to keep track of the position where the next non-zero element should be placed. This allowed me to effectively "compress" the non-zero elements to the front, implicitly leaving zeroes at the end. During the process, I leaned on dry runs to trace the array's state and visualize the pointer movements. When I hit a snag, the debugger was invaluable for stepping through the logic line by line and understanding exactly where my assumptions were off. A key takeaway for me was the power of in-place modification and how a well-placed pointer can simplify array problems significantly. How do you ⚙️ 𝗔𝗽𝗽𝗿𝗼𝗮𝗰𝗵 similar array manipulation challenges? Share your strategies below! 📦 Repo: https://lnkd.in/dSXWnSES #ArrayManipulation #JavaScript #Algorithms #ProblemSolving #CodingChallenge #DataStructures #InPlaceAlgorithms #LogicalReasoning #SoftwareDevelopment #LeetCodeStyle
To view or add a comment, sign in
-
-
When Division Is Not Allowed: Thinking in Prefix and Suffix 📊 Solved LeetCode 238 – Product of Array Except Self today. The naive solution would use division, but the constraint pushes you to think differently. The elegant approach: - Build a prefix product array (product of elements to the left) - Build a suffix product pass (product of elements to the right) - Combine them in O(n) time without extra division No nested loops. No division. Linear time. Key takeaway: Many array problems become simple when you think in terms of precomputed cumulative information. 💡 Practical insight: Whenever you see “for each element, compute something excluding itself”, think: - Prefix - Suffix - Two-pass strategy This pattern shows up in range queries, cumulative sums, and DP optimizations. #LeetCode #DSA #Arrays #JavaScript #Algorithms #ProblemSolving #LearnInPublic
To view or add a comment, sign in
-
There is nothing quite like the "Day 1" feeling of a new code space. 💻 I’m currently working through tickets and instead of just "fixing bugs," I’ve been documenting the entire journey from the initial "where does this even live?" to shipping solutions. My latest blog posts are: 𝐓𝐡𝐞 𝐀𝐫𝐭 𝐨𝐟 𝐃𝐞𝐛𝐮𝐠𝐠𝐢𝐧𝐠: Why "it works on my machine" isn't enough when dealing with cross-browser edge cases. 𝐄𝐟𝐟𝐢𝐜𝐢𝐞𝐧𝐭 𝐃𝐚𝐭𝐚 𝐇𝐚𝐧𝐝𝐥𝐢𝐧𝐠: Exploring mutating arrays and memory management. I’m sharing my full thought process and technical takeaways on my blog. Check out my latest blog post in the comments below: #BuildInPublic #Javascript #FrontendEngineering #CareerGrowth #softwareengineer #products #blog #coding
To view or add a comment, sign in
-
-
I tried implementing the internal working of forEach and map to better understand how they operate under the hood. Both are higher order functions because they accept another function as an argument. Internally, they iterate over the array (typically via a loop) and execute the callback for each element. forEach : Iterates through the array. Executes the provided callback on each element. Does not return a new array (returns undefined). Primarily used for logging map : Iterates through the array. Executes the callback on each element. Stores the callback’s return value in a new array. Returns the new transformed array. Does not mutate the original array. Rewriting these methods manually with a for loop really clarifies their behavioral difference : forEach is about execution, map is about transformation. #JavaScript #WebDevelopment #FunctionalProgramming #LearnInPublic #ChaiAurCode
To view or add a comment, sign in
-
-
Scope/Hoisting — Ghost Variable The log said undefined. You swore it should crash. It didn’t. The bug hid for weeks. Then prod got haunted. Lesson: var is hoisted and initialized to undefined. let/const are hoisted but in the Temporal Dead Zone. Prefer const, then let, avoid var. A hallway with fog. A label “TDZ” on a locked door. A shadow holding a sign: “undefined”. Caption Version (under 1200 chars): You expected a crash. You got undefined. That’s how the ghost wins. Hoisting isn’t “JavaScript being weird”. It’s JavaScript being consistent. var declarations rise up and become undefined. let/const rise up too, but stay locked in TDZ. If you want fewer hauntings: Use const by default. Use let when you must. Leave var in the basement. Digilians - الرواد الرقميون #JavaScript #CodingStory #WebDev #Scope #Hoisting #Frontend #Bugs #Digilians #MERN_STACK #TDZ
To view or add a comment, sign in
-
-
build a small practice programme: unit convertor Registry Pattern: Instead of massive if/else chains, I used a lookup object (reg) to define unit types and factors. Base Unit Normalization: I converted everything to a "Base Unit" first (e.g., meters), then to the target. This avoids needing a unique formula for every possible pair (like km -> cm). Type Validation: I added a strict check (from.type !== to.type) to prevent incompatible conversions, like trying to convert Weight to Length. Handling Exceptions: Since Temperature requires offsets (like +32) and not just multiplication factors, I separated it into its own switch case logic. #Javascript #WebDev #LearningInPublic #Coding
To view or add a comment, sign in
-
-
⚡ Day 5 – getAttribute vs setAttribute vs removeAttribute If you're working with the DOM and don’t clearly know how these behave, you’re just guessing. Here’s the clarity: 🔹 getAttribute() → Reads the attribute value 🔹 setAttribute() → Adds or updates an attribute 🔹 removeAttribute() → Removes an attribute completely Important 👇 Direct property access (like element.id or element.value) is not always the same as attribute methods. Understanding this difference makes your DOM manipulation clean, predictable, and professional. Small clarity. Big improvement. #JavaScript #WebDevelopment #FrontendDeveloper #DOM #Coding #100DaysOfCode
To view or add a comment, sign in
-
-
I thought I understood map(), filter() and reduce()… until I wrote their polyfills. We use these methods daily in JavaScript. But I wanted to understand what actually happens behind the scenes. Building polyfills is one of the best ways to master: 1️⃣ Prototypes: How inheritance actually works in JS. 2️⃣ Execution Context: Mastering the behavior of this. 3️⃣ Edge Cases: Handling reduce() accumulators without an initial value. I’ve put together a deep dive into these internals. What’s inside: The logic behind Array.prototype. Step-by-step custom implementations. The "hidden" index logic in .reduce(). Which polyfill was the hardest for you to learn? Let’s discuss below! #Javascript #Chai aur Code #Polyfills
To view or add a comment, sign in
-
Rotate Without Extra Space: Think in Transformations 🔄 Solved LeetCode 48 - Rotate Image today. The elegant trick: 1. Transpose the matrix (swap rows ↔ columns) 2. Reverse each row That’s it. No extra matrix needed. Instead of simulating rotation element by element, the problem becomes a composition of two simple transformations. Key takeaway: Hard matrix problems often reduce to recognizing the right geometric transformation. When you see the pattern, the implementation becomes clean and in-place. Another strong boost to 2D intuition. #LeetCode #DSA #Matrix #InPlaceAlgorithm #JavaScript #ProblemSolving #LearnInPublic
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