Posts

Showing posts with the label JavaScript Tutorial

🎯 What is the Event Loop in JavaScript? A Complete Guide with Diagrams

Image
🔁 What is the Event Loop in JavaScript? A Complete Guide with Diagrams Have you ever wondered how JavaScript handles asynchronous operations like setTimeout , Promises, or fetch() ? The secret lies in something called the Event Loop . In this blog post, we’ll break down: ✅ What the JavaScript Event Loop is ✅ How the Call Stack, Web APIs, and Queues work together ✅ A visual diagram to understand the flow ✅ A practical code example to clear your doubts 🔄 What is the Event Loop? JavaScript is a single-threaded language , meaning it can only do one thing at a time. But it still handles asynchronous tasks efficiently thanks to the Event Loop . Let’s understand how it works through its key components. 📊 Components of the Event Loop Call Stack: Where JavaScript tracks which function is currently running. Web APIs: Browser-provided functionalities like setTimeout , DOM Events , etc. Callback Queue: Holds callbacks from Web APIs waiting to be execut...

⚡ Throttling in JavaScript Explained with Examples

Image
Have you ever wondered how to control how often a function runs when triggered frequently — like on scroll, resize, or button click? That's where Throttling in JavaScript comes in. 📌 What is Throttling? Throttling is a technique used to limit the number of times a function gets called over time. Instead of calling the function every time an event fires, it ensures the function executes only once every specified interval. Use Case: Window resize , scroll tracking, infinite scroll, button spam protection, etc. 🧠 How Throttling Works Let’s say an event is triggered 50 times per second. With throttling, you can restrict the callback to run only once every 300ms or any interval you decide. 🛠️ Simple Example of Throttling function throttle(func, limit) { let lastFunc; let lastRan; return function(...args) { const context = this; if (!lastRan) { func.apply(context, args); lastRan = Date.now(); } else { clearTime...