SparkJS Logo
HomeIntermediateGame Loop & Animation

⚡ Game Loop & Animation

Build smooth 60 FPS games with requestAnimationFrame, delta time, and professional timing techniques

⏱️ 3.5 hours📚 9 sections⚡ Intermediate

Your Progress

0 / 9 completed

Sections

🔄

Understanding the Game Loop

Section 1 of 9

The game loop is the heartbeat of every game. It's a continuous cycle that updates game logic and renders graphics many times per second, creating the illusion of movement and interactivity. **The Three Pillars:** 1. Process Input - Handle keyboard, mouse, touch events 2. Update - Move objects, check collisions, update game state 3. Render - Draw everything to the screen **Why Do We Need a Loop?** Games are interactive simulations that respond to player input in real-time. Unlike static programs, games need to constantly update positions, check for collisions, animate sprites, and redraw the screen. **The Classic Game Loop Pattern:** • Run continuously at a target frame rate (usually 60 FPS) • Each iteration is called a "frame" or "tick" • Smooth gameplay requires consistent timing • Must handle both fast and slow devices gracefully **Frame Rate vs Refresh Rate:** • Frame Rate: How many times your game updates per second • Refresh Rate: How many times the monitor updates per second • Target: 60 FPS to match most monitors (16.67ms per frame)

💻Code Example

// Basic game loop structure
function gameLoop() {
  // 1. Process Input
  handleInput();
  
  // 2. Update Game State
  updatePlayer();
  updateEnemies();
  checkCollisions();
  updatePhysics();
  
  // 3. Render
  clearScreen();
  drawBackground();
  drawPlayer();
  drawEnemies();
  drawUI();
  
  // Continue the loop
  requestAnimationFrame(gameLoop);
}

// Start the game
requestAnimationFrame(gameLoop);

// Simple example with a moving box
let x = 0;

function simpleLoop() {
  ctx.clearRect(0, 0, canvas.width, canvas.height);
  
  // Update
  x += 2;
  if (x > canvas.width) x = 0;
  
  // Draw
  ctx.fillStyle = 'blue';
  ctx.fillRect(x, 100, 50, 50);
  
  requestAnimationFrame(simpleLoop);
}

🎯 Key Takeaways

  • Use requestAnimationFrame for smooth, browser-optimized animation loops
  • Always use delta time for frame-independent movement and physics
  • Monitor FPS to detect performance issues early in development
  • Fixed time step provides deterministic physics for professional games
  • State machines keep game code organized and maintainable

🚀 Practice Challenge

Build a smooth platformer demo showcasing game loop mastery:

  • 1.Implement a player character with smooth movement using delta time
  • 2.Add gravity and jumping physics with fixed time step
  • 3.Create animated sprites that change based on player state
  • 4.Display FPS counter and frame time in the corner
  • 5.Implement pause functionality with state management
Try the Challenge →

📚 Next Lesson

💥 Collision Detection

Master AABB, circle, and advanced collision algorithms

Continue Learning →