Day 14/30 – Cancelable Function with Timeout in JavaScript Challenge ⏳❌ | Async 💻🚀 🧠 Problem: Create a function that: Delays execution of fn by t milliseconds Returns a cancel function (cancelFn) If cancelFn is called before the delay ends → execution is canceled If not canceled → fn runs with the given arguments ✨ What this challenge teaches: Timer management using setTimeout Cancellation patterns in async JavaScript Controlling execution flow — a key skill for real-world apps This concept is used in: ⚡ Debouncing & throttling ⚡ API request cancellation ⚡ User interaction handling ⚡ Performance optimization Example 1: Input: fn = (x) => x * 5, args = [2], t = 20 Output: [{"time": 20, "returned": 10}] Explanation: const cancelTimeMs = 50; const cancelFn = cancellable((x) => x * 5, [2], 20); setTimeout(cancelFn, cancelTimeMs); The cancellation was scheduled to occur after a delay of cancelTimeMs (50ms), which happened after the execution of fn(2) at 20ms. Constraints: fn is a function args is a valid JSON array 1 <= args.length <= 10 20 <= t <= 1000 10 <= cancelTimeMs <= 1000 💬 Where would you use cancelable logic in a real project? #JavaScript #30DaysOfJavaScript #CodingChallenge #AsyncJavaScript #Closures #JSLogic #LeetCode #WebDevelopment #LearnToCode #CodeEveryday #DeveloperJourney #Programming #TechCommunity JavaScript cancelable function setTimeout cancel execution Async function cancellation JS JavaScript debounce logic LeetCode JavaScript solution JS interview questions Advanced JavaScript concepts Daily coding challenge
Cancelable Function with Timeout Challenge in JavaScript
More Relevant Posts
-
Understanding "let" Scope in JavaScript (Global, Function, and Block Scope) 1️⃣ Global Scope When a variable is declared outside any function or block using "let", it becomes a global variable and can be accessed anywhere in the program. let username = "Ali"; function showUser() { console.log(username); } showUser(); // Ali Here, "username" is declared globally, so it can be accessed inside the function as well. --- 2️⃣ Function Scope When "let" is declared inside a function, it can only be accessed within that function. function test() { let number = 10; console.log(number); // 10 } test(); console.log(number); // Error: number is not defined The variable "number" only exists inside the function "test()". --- 3️⃣ Block Scope One of the biggest advantages of "let" is block scope. If a variable is declared inside a block "{ }", it can only be used inside that block. if (true) { let message = "Hello"; console.log(message); // Hello } console.log(message); // Error: message is not defined Here, "message" is limited to the "if" block only. --- ✅ Key Point - "let" respects Global Scope - "let" respects Function Scope - "let" respects Block Scope Because of this predictable behavior, developers prefer "let" and "const" over "var" in modern JavaScript. 💡 Understanding scope helps you write cleaner and more reliable code. #JavaScript #WebDevelopment #BackendDevelopment #Programming
To view or add a comment, sign in
-
Day 11: Callback Functions in JavaScript JavaScript is single-threaded… so how does it handle async tasks? 🤔 The answer starts with Callbacks. 🔹 What is a Callback? A callback function is a function that is: ✅ Passed as an argument to another function ✅ Executed later 🔹 Basic Example function greet(name) { console.log("Hello " + name); } function processUser(callback) { const name = "Shiv"; callback(name); } processUser(greet); Here, greet is a callback function. 🔹 Async Example setTimeout(function() { console.log("Executed after 2 seconds"); }, 2000); 👉 The function runs after a delay 👉 JavaScript does not block execution 🔥 Why Callbacks Are Important ✔️ Foundation of async JavaScript ✔️ Used in APIs, event listeners, timers ✔️ Core concept before learning Promises ⚠️ The Problem: Callback Hell When callbacks are nested too much: api1(function() { api2(function() { api3(function() { console.log("Done"); }); }); }); This leads to: ❌ Hard-to-read code ❌ Pyramid structure ❌ Difficult debugging This problem was later solved using Promises and Async/Await. #Javascript #CallBack #webdevelopment #LearnInPublic
To view or add a comment, sign in
-
🚀 Understanding "var" Scope in JavaScript In JavaScript, there are mainly three types of scope: 1️⃣ Global Scope – Variables declared outside any function are accessible everywhere in the program. 2️⃣ Function Scope – Variables declared inside a function can only be used inside that function. 3️⃣ Block Scope – Variables declared inside blocks like "{ }" (for example in "if", "for", etc.) are only accessible inside that block. However, the important thing to remember is: 👉 The "var" keyword only follows Global Scope and Function Scope. ❌ It does NOT follow Block Scope. Let’s look at a simple example: if (true) { var message = "Hello World"; } console.log(message); // Output: Hello World Even though "message" is declared inside the "if" block, we can still access it outside the block. This happens because "var" ignores block scope. Now look at a function example: function test() { var number = 10; console.log(number); // 10 } console.log(number); // Error: number is not defined Here, "number" is declared inside the function, so it cannot be accessed outside the function. ✅ Key Takeaway: - "var" → Global Scope + Function Scope - "var" ❌ does not support Block Scope That’s why modern JavaScript developers prefer "let" and "const", because they properly support block scope. #JavaScript #WebDevelopment #Programming #BackendDevelopment
To view or add a comment, sign in
-
👨💻Mastering JavaScript — One Concept at a Time (4/32) Operators are the verbs of your code. While revisiting JavaScript fundamentals, I noticed something interesting: 🔹 What Are Operators? Operators are symbols that tell JavaScript to perform an operation. They allow us to: Calculate values, compare data, make decisions, combine logic and modify variables. 1️⃣ Arithmetic Operators These are the most familiar ones used for mathematical operations. Addition, subtraction, multiplication, division, modulus, and exponentiation. But even here, JavaScript has quirks. For example, + is not just addition, but also performs string concatenation. That dual behaviour is something I now pay close attention to. 2️⃣ Comparison Operators These help us compare values; they return a boolean (true or false). Important distinction: Loose comparison (==) Strict comparison (===) Earlier in this series, I discussed why strict comparison is usually safer. Revisiting this again reinforces how small operator choices can prevent big bugs. 3️⃣ Logical Operators These are used for combining conditions: AND (&&), OR (||), NOT (!). What I appreciate now is that logical operators don’t just return true or false they return actual values based on truthy and falsy evaluation.That subtle behavior is powerful in real-world applications. 4️⃣ Unary Operators Unary operators work with a single operand. Examples include: Increment (++), Decrement (--), typeof, Logical NOT (!). They seem simple, but understanding how they affect state (especially in loops) matters a lot. ❓ Ternary Operator The ternary operator is JavaScript’s compact decision-maker. It’s a shorthand for if...else. Clean and readable when used properly. Confusing and messy when overused. I’ve learned that readability should always come before cleverness. 💡 Learning Mindset While revising this, I’m not just memorising operators. I’m asking: What exactly does this operator return? Does it mutate the value? Is it safe and readable? What operator confused you the most when you first learned JavaScript? #JavaScript #LearningInPublic #WebDevelopment #FrontendDevelopment #MasteringJavaScript
To view or add a comment, sign in
-
"Struggling to untangle the web of asynchronous JavaScript code? 😩 Promises and async/await are powerful, but debugging them can feel like navigating a maze! I often get asked: "How do I effectively debug asynchronous code (Promises, async/await) in JavaScript?" Here's a quick tip to get you started: 1. Use the Browser's Debugger: Modern browsers offer excellent debugging tools. Set breakpoints within your `then()` or `await` blocks to pause execution and inspect variables. Use the "Step Over," "Step Into," and "Step Out" buttons to follow the code's execution flow. 2. Console.log is Your Friend (But Use Sparingly): While `console.log()` can be helpful, avoid cluttering your code. Strategically place `console.log()` statements to check the values of variables at different points in your asynchronous operations. 3. Learn to Read the Call Stack: When an error occurs, the call stack will show you the sequence of function calls that led to the error. Understanding the call stack is crucial for tracing the source of asynchronous errors. 4. **Consider Using a Debugging Library:** For more complex scenarios, libraries like `debug` or dedicated debugging tools can provide enhanced logging and tracing capabilities. What are your favorite tips for debugging asynchronous JavaScript? Share them in the comments! Let's help each other conquer this common challenge. 👇 #javascript #debugging #asyncawait #promises #webdevelopment #softwareengineering #programming #frontend #nodejs #angular"
To view or add a comment, sign in
-
-
🚀 5 Advanced JavaScript Concepts Every Developer Should Understand As you move beyond the basics in JavaScript, understanding some deeper concepts becomes very important. These concepts help you write better code, debug complex issues, and understand how JavaScript actually works behind the scenes. Here are 5 advanced JavaScript concepts every developer should know. 1️⃣ Closures Closures occur when a function remembers variables from its outer scope even after that outer function has finished executing. They are commonly used in callbacks, event handlers, and data privacy patterns. 2️⃣ The Event Loop JavaScript is single threaded, but it can still handle asynchronous operations through the Event Loop. Understanding the call stack, task queue, and microtask queue helps explain how asynchronous code runs. 3️⃣ Debouncing and Throttling These techniques control how often a function executes. They are extremely useful when handling events like scrolling, resizing, or search input to improve performance. 4️⃣ Prototypal Inheritance Unlike many other languages, JavaScript uses prototypes to enable inheritance. Understanding prototypes helps you understand how objects share properties and methods. 5️⃣ Currying Currying is a functional programming technique where a function takes multiple arguments one at a time. It allows you to create more reusable and flexible functions. Mastering concepts like these helps developers move from simply writing JavaScript to truly understanding how it works. Which JavaScript concept took you the longest to understand? #JavaScript #WebDevelopment #Programming #Developers #FrontendDeveloper
To view or add a comment, sign in
-
-
Understanding the JavaScript Event Loop is a game changer for writing efficient asynchronous code. Many developers use setTimeout and Promise daily — but fewer truly understand what happens behind the scenes. Here’s a quick breakdown 👇 🔹 JavaScript is single-threaded 🔹 Synchronous code runs first (Call Stack) 🔹 Then all Microtasks execute (Promises, queueMicrotask) 🔹 Then one Macrotask runs (setTimeout, setInterval, DOM events) 🔹 The loop repeats 📌 Execution Priority: Synchronous → Microtasks → Macrotasks Example: console.log(1); setTimeout(() => console.log(2), 0); Promise.resolve().then(() => console.log(3)); console.log(4); ✅ Output: 1 → 4 → 3 → 2 Understanding this helps in: ✔ Debugging async issues ✔ Optimizing performance ✔ Writing better React applications ✔ Cracking frontend interviews I’ve created a simple infographic to visually explain the entire Event Loop process. If you're preparing for JavaScript or React interviews, mastering this concept is essential. 💬 Now Your Turn 👇 What will be the output of this code? console.log("A"); setTimeout(() => console.log("B"), 0); Promise.resolve().then(() => { console.log("C"); }); console.log("D"); 👨💻 Follow for daily React, and JavaScript 👉 Ashish Pimple Drop your answer in the comments 👇 Let’s see who really understands the Event Loop 🔥 hashtag #JavaScript hashtag #FrontendDevelopment hashtag #ReactJS hashtag #WebDevelopment hashtag #EventLoop hashtag #CodingInterview
To view or add a comment, sign in
-
-
Day 18/30 – Debounce Function in JavaScript Challenge ⏳🚀 | Optimize Performance Like a Pro 💻🔥 🧠 Problem: Create a debounced version of a function: Execution is delayed by t milliseconds If called again within that time → previous call is canceled Only the last call executes after the delay Example behavior: If calls happen too quickly → earlier ones are ignored Only the final call within the time window runs ✨ What this challenge teaches: Advanced timer control Managing rapid user interactions Writing performance-optimized code Debouncing is used in: ⚡ Search bars (API calls) ⚡ Auto-save features ⚡ Resize/scroll events ⚡ Input validation This is a must-know concept for frontend developers. 💬 Where have you used debouncing in your projects? #JavaScript #30DaysOfJavaScript #CodingChallenge #Debounce #FrontendDevelopment #PerformanceOptimization #JSLogic #WebDevelopment #LearnToCode #CodeEveryday #DeveloperJourney #Programming #TechCommunity JavaScript debounce function Implement debounce from scratch Debounce vs throttle JavaScript Performance optimization JS LeetCode JavaScript solution JS interview questions Advanced JavaScript concepts Daily coding challenge
To view or add a comment, sign in
-
-
🚨 JavaScript Developers — Have you heard about the new try operator proposal in ECMAScript? If you write JavaScript regularly, this is something worth knowing 👇 A new Stage 0 proposal suggests introducing a try <expression> operator that converts exceptions into values. Instead of writing multiple nested try/catch blocks, developers could handle errors in a much cleaner and more readable way. Example: const [ok, error, data] = try JSON.parse(input) if (!ok) { console.error(error) } This approach separates the happy path from error handling, reducing nesting and improving readability. It works somewhat like await, but for error handling: const result = try await fetch("/api/users") Key idea: • Execute an expression • If it throws → return { ok: false, error } • If it succeeds → return { ok: true, value } Why this matters: ✅ Cleaner error handling ✅ Less nested try/catch blocks ✅ More readable control flow The proposal is currently Stage 0, meaning it's still early and may or may not become part of the language. But it's an interesting direction for improving JavaScript ergonomics. If you're interested in the future of JavaScript, it's definitely worth reading about this proposal. 👉 JavaScript developers — what do you think? Would you use a try operator like this in your code? #javascript #ecmascript #webdevelopment #programming #softwareengineering
To view or add a comment, sign in
-
Day 24/30 – Sort an Array by Function Output in JavaScript Challange🔢 | Custom Comparator 📌 Problem Given: An array arr A function fn Return a new array sortedArr sorted in ascending order based on the value returned by fn(arr[i]). You can assume: fn always returns a number Sorting must be based on fn output 🧠 Example arr = [5, 4, 1, 2, 3] fn = (x) => x * x Since squares are: 25, 16, 1, 4, 9 Sorted by square value: [1, 2, 3, 4, 5] 💡 JavaScript Solution var sortBy = function(arr, fn) { return arr.slice().sort((a, b) => fn(a) - fn(b)); }; 🔎 Why This Works sort() accepts a comparator fn(a) - fn(b) ensures ascending order slice() prevents mutation of the original array Time Complexity: O(n log n) Space Complexity: O(n) (due to copy) ⚡ Real-World Use Cases Sorting users by age Sorting products by price Ranking students by score Sorting tasks by priority 🧠 Interview Insight This pattern is called “sort by projection”: You don’t sort by the element itself — You sort by a derived value. That’s a powerful abstraction concept. #JavaScript #30DaysOfJavaScript #CodingChallenge #JSLogic #ArrayMethods #WebDevelopment #FrontendDevelopment #LearnToCode #CodeEveryday #Programming #DeveloperJourney #TechCommunity #InterviewPrep #LeetCode #AsyncJavaScript #SoftwareEngineering #100DaysOfCode #BuildInPublic Custom comparator JavaScript Sort array by derived value JS JavaScript array sort interview question Higher order functions JavaScript JavaScript sorting techniques JS sort with callback Advanced JavaScript array methods JavaScript coding challenge solution Frontend interview preparation
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