JavaScript Gotcha #3: The setTimeout Loop That Lied to Me While building an animation sequence, I needed to log a series of numbers with delays using the setTimeout function. So I wrote the code in the picture expecting output as "1, 2, 3, 4, 5" but it printed "6, 6, 6, 6, 6, 6". Classic JavaScript. After a brief (and mandatory) panic, I realised the problem: "var" is function-scoped, not block-scoped. So by the time the timeouts executed, the loop had already finished, and "i" was 6. Here's the simple fix: Use "let", which is block-scoped and preserves the correct value for each iteration, and now it works perfectly. Lesson learned: When using async callbacks inside loops, scope matters. "let" doesn’t just fix bugs — it saves your sanity.
JavaScript Gotcha: Using "let" in setTimeout Loop
More Relevant Posts
-
Skill Upgrade Alert: Building High-Performance 3D Animations with Pure CSS Why rely on heavy JavaScript libraries when CSS3 can deliver stunning 3D effects? I've released a new tutorial demonstrating how to create this rotating text spiral animation using only performant HTML and CSS. This is an excellent lesson in mastering CSS transform-style: preserve-3d; and advanced @keyframes—skills essential for modern, high-performance frontend development. Check out the full breakdown: Video Walkthrough: https://lnkd.in/ep4RhhJJ Article & Code Snippets: https://lnkd.in/etsxwC9R Looking for deeper learning or customized help? Book: https://lnkd.in/ej7Jcv9b Course: https://lnkd.in/e73PE8GF One-on-one Tutorials: https://ojambo.com/contact #Frontend #WebDevelopment #CSS3 #CodingSkills #PerformanceMatters #JavaScript
To view or add a comment, sign in
-
🚀 Created a fun web mini-application that simulates a flight takeoff countdown using JavaScript’s setInterval() function. 💡 How it works: The countdown starts from 10 and updates every second. As it approaches zero, the text color changes to red — adding a sense of urgency. When the timer hits 0, the image switches to a flying airplane GIF, symbolizing the flight taking off! 🛠️ Tech Used: HTML for structure CSS for design and gradients JavaScript for countdown logic and DOM updates 🎯 What I learned: How to use timers (setInterval, clearInterval) effectively Dynamic DOM manipulation with JavaScript Simple UI enhancements using CSS transitions and effects This small project gave me a fun way to connect logic and visuals, turning a simple countdown into a real-time interactive animation. #JavaScript #WebDevelopment #Frontend #MiniProject #LearningByDoing #CSS #HTML #FlightSimulation 10000 Coders Usha Sri Manoj Kumar Reddy Parlapalli
To view or add a comment, sign in
-
Here’s a fun #p5js sketch I worked on a while ago: a tiny planetary system with interactive comets you can slingshot around. Everything is generated dynamically with JavaScript! Creative coding is really just playing with simple building blocks and seeing how they interact. Things like Perlin Noise for nebulas or masking for grain can create surprisingly rich effects. If you’re curious about experimenting with these techniques, I put together a free resource with 30 digestible p5.js building blocks, from the basics of drawing shapes to integrating sound and 3D effects in your sketches: https://lnkd.in/eFp6sjT5
To view or add a comment, sign in
-
🌊 Just recreated this mesmerizing WebGL distortion effect! Inspired by the stunning work at https://lnkd.in/gKxtcUsm , I built an interactive image distortion system using Three.js that responds to mouse/touch movements. ✨ Features: Real-time flowmap-based distortion Chromatic aberration for that prismatic effect Smooth motion blur trails Fully responsive on all devices The magic happens through shader programming - calculating velocity fields, warping UV coordinates, and splitting RGB channels to create that liquid, flowing aesthetic. Always exciting to break down complex visual effects and bring them to life! 🚀 #WebGL #ThreeJS #CreativeCoding #FrontendDevelopment #JavaScript #ShaderProgramming
To view or add a comment, sign in
-
Built a Classic Snake Game using HTML, CSS, and JavaScript This project was an exciting opportunity to combine logic, creativity, and design into a single experience. The game includes: • Smooth snake movement controlled by keyboard input • Collision detection for handling game-over scenarios • Dynamic food generation and score tracking • A clean and responsive layout for a better user experience Through this project, I deepened my understanding of: • DOM manipulation and rendering logic • Event listeners and keyboard handling • CSS grid layout for game design • Game loop and animation logic in JavaScript Building this reminded me how even simple games can teach powerful programming principles like loops, conditionals, and real-time updates. Always keep building and experimenting — that’s how real learning happens. I’d love to hear your thoughts and feedback. #HTML #CSS #JavaScript #WebDevelopment #Frontend #SnakeGame #CodingJourney
To view or add a comment, sign in
-
Modern Card Hover Animations, CSS and JavaScript A great hover effect can make user interfaces feel alive it's a small detail that adds visual polish and depth. This article will cover hover effects on cards, walking through three custom-made variations for a card's background. The main idea? Adding unique twists to the classic subtle glow where your mouse hovers. As usual with my articles, expect imagery, code examples, and a live demo at the end! For this, I'll be using HTML Canvas, CSS, JavaScript, and React. But you can follow along with the ideas regardless of your tooling if you prefer GSAP or no React at all, that's fine too. The first is the classic: When the mouse hovers over a card, add a glow beneath the cursor. Simple, no? The second, is quite a bit more interesting, it will use HTML Canvas and :before to apply a blur over the canvas. But what will the canvas do? Well, the idea is to make a pixelated, almost dithered hover effect. If you are curious about dithering, here is a cool dithered shadow on CodePen similar to wha https://lnkd.in/gq_ArGvD
To view or add a comment, sign in
-
Modern Card Hover Animations, CSS and JavaScript A great hover effect can make user interfaces feel alive it's a small detail that adds visual polish and depth. This article will cover hover effects on cards, walking through three custom-made variations for a card's background. The main idea? Adding unique twists to the classic subtle glow where your mouse hovers. As usual with my articles, expect imagery, code examples, and a live demo at the end! For this, I'll be using HTML Canvas, CSS, JavaScript, and React. But you can follow along with the ideas regardless of your tooling if you prefer GSAP or no React at all, that's fine too. The first is the classic: When the mouse hovers over a card, add a glow beneath the cursor. Simple, no? The second, is quite a bit more interesting, it will use HTML Canvas and :before to apply a blur over the canvas. But what will the canvas do? Well, the idea is to make a pixelated, almost dithered hover effect. If you are curious about dithering, here is a cool dithered shadow on CodePen similar to wha https://lnkd.in/gq_ArGvD
To view or add a comment, sign in
-
useEffect vs useLayoutEffect — the difference that actually matters! Most devs use useEffect for everything, but here’s what’s happening under the hood 👇 useEffect: Runs after the paint (i.e., after the screen updates). ✅ Great for API calls, event listeners, or logging. 🚫 Avoid for DOM measurements or layout changes — you’ll see a flicker. useLayoutEffect: Runs before the paint (right after DOM mutations but before the browser updates the screen). ✅ Perfect for reading layout, measuring elements, or synchronizing animations. 🚫 Avoid overusing it — it can block rendering and hurt performance. 💡 Quick rule: If it affects what you see → use useLayoutEffect If it affects after you see → use useEffect 💬 What’s your go-to use case for useLayoutEffect? Let’s make this a mini thread of learnings 👇 #ReactJS #FrontendDevelopment #WebDevelopment #useEffect #CodingTips #JavaScript #LearnInPublic
To view or add a comment, sign in
-
-
#day2of365daysofcode CSS animations do not just move elements. They bring a page to life. In this post, I am sharing examples that show how each @keyframes property actually behaves in action. If you are learning frontend, understanding animations is a huge step toward building smooth, engaging user experiences. Watch. Practice. Experiment. Your UI magic level goes up each time. Save for later and tag someone learning CSS. I’m challenging myself to post one piece of tech learning every day for the next 365 days. Today is Day 2. #day2of365daysofcode #frontenddevelopment #css #cssanimations #webdevelopment #programming #javascript #html #codingjourney #learncoding #developercommunity #techlearning #uiuxdesign #365daysofcode #webdev
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