Please enable JavaScript to use CodeHS

Games & Animations with Three.js

The Animation Loop in Three.js

Six parts ago you wrote cube.rotation.y += 0.01 and it just worked. In this part you find out what that line secretly depends on, why old games ran faster on faster computers, and the one habit that keeps your game at the same speed on every screen.

Part 7 of 12 ~15 min JavaScript
Part 7 of 12

What you'll learn

  • What renderer.setAnimationLoop(animate) really does: it asks the browser to call your function once per screen refresh, and that number is not the same on every device.
  • Why rotation.y += 0.01 runs twice as fast on a 120 Hz monitor and half as fast on a laptop that is struggling.
  • How THREE.Clock and getDelta() let you write speeds in units per second, so your game plays the same everywhere.
  • The three loop patterns you will use in every game: constant motion, bobbing with Math.sin, and a countdown timer.

The Big Idea

Animation is a flipbook

Nothing on a screen actually moves. A flipbook is a stack of drawings, each a tiny bit different from the last, and when you flip through them fast enough your brain sees motion. Your three.js scene works the same way. Each drawing is called a frame. The animation loop is the part of your program that draws a new frame, changes things a little, draws again, and never stops. Every += 0.01 in Parts 1 through 6 was one flip of the book.

The line that starts the loop is renderer.setAnimationLoop(animate). It hands your animate function to the browser and says: call this every time the screen is about to refresh. Under the hood it uses the browser's requestAnimationFrame, and it adds two favors. It pauses the loop automatically when the tab is hidden, so your game does not drain the battery in a background tab. And it is the only way to run a loop in WebXR, so learning it now means nothing to unlearn later.

Here is the part that changes how you write games. Most screens refresh 60 times a second, so animate runs about 60 times a second, and a frame lasts about 16 milliseconds. But a gaming monitor refreshes 120 or 144 times a second. A cheap laptop with ten tabs open might manage only 30. The browser calls your function once per refresh, whatever the refresh rate is. The frame rate, measured in frames per second (fps), is not something you choose. It is something you have to live with.

Now look at cube.rotation.y += 0.01 again. It adds 0.01 radians per frame. At 60 fps that is 0.6 radians a second. On a 120 Hz monitor the same line runs 120 times a second and the cube spins twice as fast. On the struggling laptop it spins at half speed. If you are reading this on a 120 Hz screen, the "per frame" cube in the hero stage is already spinning twice as fast as the "per second" cube next to it, and nothing in the code changed.

This is not a made-up problem. Many games from the 1980s and 1990s moved everything per frame, and when faster computers came out they became unplayable: enemies zipped around at double speed, and some PCs shipped with a "turbo" button whose real job was to slow the machine down so old games worked. Movement in games, and later physics, must be written per second, not per frame. That is what the rest of this page is about.

Simple definition: a frame is one drawing of the scene. The frame rate is how many frames the screen shows per second, and it varies from device to device. Delta time (dt) is how many seconds have passed since the previous frame, about 0.016 at 60 fps. Multiply a speed by dt and your motion becomes "per second" instead of "per frame."


How It Works

Frames, clocks, and delta time

We keep the setup from Part 1: scene, camera, renderer, and a lit cube. The only code that changes on this page is the loop itself, and the change is three lines.

1. The loop you already have

This is the loop from Part 1, with one honest comment added. It is not wrong, exactly. It just makes a promise it cannot keep: that a frame is always 1/60 of a second.

loop-per-frame.js
// The loop from Part 1. The browser calls animate() once per screen refresh.
function animate() {
  cube.rotation.y += 0.02;   // 0.02 radians PER FRAME. At 60 fps that is 1.2 rad/s.
                             // At 120 fps it is 2.4 rad/s. At 30 fps, 0.6 rad/s.
                             // The cube's speed depends on the player's screen.
  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);   // start the flipbook (wraps requestAnimationFrame)

This drives the "per frame" cube in both stages. Part 1 used 0.01; we use 0.02 here only so it matches the other cube's speed at 60 fps and the race is fair.

2. The fix: measure time, then multiply

The fix is to stop counting frames and start measuring time. THREE.Clock is a stopwatch. Create one, outside the loop, and each frame ask it clock.getDelta(): how many seconds since the last time I asked? That number is the delta time, usually written dt. At 60 fps it is about 0.016. At 120 fps it is 0.008. On the struggling laptop it is 0.033.

Now write your speed in units per second and multiply by dt. If SPEED is 1.2 radians per second, then SPEED * dt is 1.2 × 0.016 = 0.02 radians on a 60 fps frame, and 1.2 × 0.008 = 0.01 on a 120 fps frame. Twice as many frames, each moving half as far. After one second the cube has turned exactly 1.2 radians either way. Pick Math.PI as the speed and you get half a turn every second, no matter the frame rate, on any device. That property has a name: frame-rate independence.

One more line makes it safe. Remember that the loop pauses when the tab is hidden. When the player comes back after a minute, the first getDelta() returns 60, and SPEED * 60 teleports every object across the level in one frame. Clamp it: Math.min(clock.getDelta(), 0.1) says a frame never counts for more than a tenth of a second, however long it really took. The stages on this page do the same thing every time you scroll them back on screen.

loop-per-second.js
// A stopwatch. Make ONE, outside the loop, next to the scene and camera.
const clock = new THREE.Clock();
const SPEED = 1.2;   // radians PER SECOND (Math.PI would be half a turn every second)

function animate() {
  // Seconds since the last frame: ~0.016 at 60 fps, ~0.008 at 120, ~0.033 at 30.
  // Read it ONCE per frame and store it. The clamp means a tab that was hidden
  // for a minute counts as 0.1 s when it comes back, instead of teleporting things.
  const dt = Math.min(clock.getDelta(), 0.1);

  cube.rotation.y += SPEED * dt;   // 1.2 rad every second, on every screen

  renderer.render(scene, camera);   // always last: draw the world AFTER you change it
}
renderer.setAnimationLoop(animate);

This drives the "per second" cube. The Speed slider below is SPEED, and the live code shows what SPEED * dt works out to on the frame you are looking at.

3. Three loop patterns you will use in every game

Almost everything that moves in a game is one of three shapes of code. Each one is a few lines, and each one uses the clock.

x += speed * dt

constant motion

A car driving, a bullet flying, a cube spinning. Speed is in units per second; dt turns it into this frame's share. Part 10 drives a player with it.

y = Math.sin(t * 2) * 0.5

oscillation

A coin bobbing, a boss "breathing," a floating platform. t is clock.getElapsedTime(), the seconds since the start. No adding up, so it can never drift.

timeLeft -= dt

a countdown

A 20-second round, a power-up that wears off, a respawn delay. Subtract dt each frame and check for zero. Part 17 builds a whole game around it.

The middle one deserves a closer look. clock.getElapsedTime() returns the total seconds since the clock started. Math.sin of a number that keeps growing swings smoothly between -1 and 1 forever, so Math.sin(t * 2) * 0.5 is a value that bobs between -0.5 and 0.5, completing a full up-and-down every π seconds. The * 2 is how fast it bobs; the * 0.5 is how far. Notice it uses =, not +=: the position is computed from time rather than nudged each frame, which is why it does not care about the frame rate at all.

patterns.js
const clock = new THREE.Clock();
let timeLeft = 20;   // seconds in the round

function animate() {
  const dt = Math.min(clock.getDelta(), 0.1);   // read dt FIRST, once
  const t = clock.getElapsedTime();              // seconds since the start

  // 1. Constant motion: 3 units per second, whatever the frame rate
  car.position.x += 3 * dt;

  // 2. Oscillation: bob between -0.5 and 0.5, a full cycle every PI seconds
  coin.position.y = Math.sin(t * 2) * 0.5;

  // 3. A countdown: subtract the seconds that passed, then check
  timeLeft -= dt;
  if (timeLeft <= 0) {
    timeLeft = 0;
    endRound();   // Part 17: switch the game state to "gameover"
  }

  renderer.render(scene, camera);
}
renderer.setAnimationLoop(animate);

The bobbing sphere in the "Try it" stage is line 2 exactly. Under the hood, getElapsedTime() calls getDelta() for you, which is why dt is read first.

4. Three habits around the loop

Render last. renderer.render(scene, camera) takes a photo of the scene as it is at that instant. Move things first, then take the photo. Render first and every frame shows the world as it was one frame ago; the game still runs, but everything feels a hair late, and collision checks in Part 15 will look like they happen a frame after the hit.

Stop with null. renderer.setAnimationLoop(null) stops the loop. You will use it for pause menus, and the stages on this page use it to stop drawing when they scroll off screen. Pass animate again to resume.

Keep heavy work out of the loop. The loop runs 60 times a second, so anything inside it runs 60 times a second. Creating a new THREE.BoxGeometry() or a new material inside animate builds 3,600 copies a minute and, as Part 3 warned, none of them are freed unless you dispose() them. Build objects once, before the loop starts, and only change numbers inside it.


Try It

The slow-device test

Two identical cubes. The left one runs loop-per-frame.js; the right one runs loop-per-second.js. Under each is a lap counter: how many full turns it has completed since you last reset. The sphere in the middle is the bobbing pattern. On a normal 60 Hz screen the two cubes keep pace, and that is exactly what makes the bug hard to notice. The two Simulate buttons change the frame rate the loop experiences, so you can see what a player on a different device would see. The chip in the corner shows the real frame rate and this frame's dt.

The simulations are honest about what they do, but they are simulations: "slow device" skips frames inside animate so only one in three is updated and drawn, and "120 Hz" runs the update twice per real frame. Neither changes your actual monitor.

1.20 rad/s · 0.19 turns/s
0.020
Simulate a different device changes how often the loop gets to update, not your monitor
Scene and playback the sphere is pattern 2; Reset laps zeroes both counters
Live code: inside animate(), this frame
const dt = Math.min(clock.getDelta(), 0.1);   // 0.017 s this frame, 60 fps
perSecond.rotation.y += 1.20 * dt;   // += 0.0200 this frame, always 1.20 rad/s
perFrame.rotation.y  += 0.020;        // += 0.0200 this frame: 1.20 rad/s at 60 fps, 0.40 at 20, 2.40 at 120
sphere.position.y = Math.sin(clock.getElapsedTime() * 2) * 0.5;   // t = 0.0 s, y = 0.00
// normal: one update and one render per screen refresh
renderer.setAnimationLoop(animate);
  1. Press Reset laps, turn on Simulate a slow device, and count for ten seconds. The per-second cube finishes about 2 laps, the same as before, because 1.2 rad/s × 10 s is always 12 radians. The per-frame cube manages well under 1: it only gets to add 0.02 twenty times a second now. Same code, same ten seconds, a third of the motion. This is what a player on a weak laptop would see in a per-frame game.
  2. Turn the simulation off and drag Speed to 3.0 rad/s. The per-second cube pulls ahead. Now make the per-frame cube match it at 60 fps: it needs 3.0 ÷ 60 = 0.05 radians per frame, so set Increment to 0.050 and press Reset laps. The counters climb together again. Then flip Simulate a slow device back on: the match was never real, it only held at exactly 60 fps.
  3. Reset laps and turn on Simulate a fast 120 Hz display. Watch which cube speeds up. The per-frame cube doubles, because it now adds its increment twice per real frame. The per-second cube does not change at all: it gets two updates too, but each one is SPEED * (dt / 2), and two halves make the same whole. Whatever you do to the frame rate, the bobbing sphere never changes either, because its height is computed from the clock, not accumulated.

Watch Out

Common mistakes

Loop bugs are the sneakiest kind, because the game works perfectly on your computer. They show up as "it's way too fast on my friend's PC," a cube that never moves, or a jump that happens a frame late.

"It plays differently on every device"

Your game feels right on your laptop, is frantic on a friend's 144 Hz gaming monitor, and sluggish on a Chromebook. Every movement line in the loop is a plain += 0.05.

Fix: this whole page. Make one THREE.Clock, read const dt = Math.min(clock.getDelta(), 0.1) at the top of the loop, and write every speed as units per second times dt. Flip the slow-device toggle above to test your own game's logic in your head: would this line survive it?

new THREE.Clock() inside the loop

You wrote const clock = new THREE.Clock() on the first line of animate, and nothing moves. dt is always 0.

Fix: a brand-new stopwatch has nothing to compare against, so its first getDelta() is 0, and you are making a brand-new one every frame. Create the clock once, outside the loop, next to the scene and camera. The stopwatch has to keep running between frames to measure them.

getDelta() twice in one frame

The player moves with 3 * clock.getDelta(), and a few lines later the enemy moves with 2 * clock.getDelta(). The player moves; the enemy is frozen.

Fix: getDelta() means "since the last time you asked," and you just asked a microsecond ago, so the second call returns about 0. Read it once into const dt and use that variable everywhere in the frame. getElapsedTime() calls getDelta() internally, so read dt before it, as patterns.js does.

No render, or render first

Either the cube's rotation number is climbing in the console and the picture never changes, or everything works but reactions feel a hair late.

Fix: changing numbers does not draw anything; renderer.render(scene, camera) does, so it has to be inside the loop. And it has to be the last line: render takes a snapshot of the scene as it is right then, so move things first, then snap. Rendering first shows the previous frame's positions forever.


Your Turn

Check your understanding

A character should walk 3 units per second, on every device. Write the one line inside the loop that moves it, and name the variable it needs from THREE.Clock and where that variable comes from.

Your answer:

Sample answer: player.position.x += 3 * dt;. The variable is dt, the delta time, read once at the top of the loop with const dt = clock.getDelta(); (clamped with Math.min(..., 0.1) if you want to be safe), where clock is a single new THREE.Clock() created outside the loop. 3 is the speed in units per second; dt is this frame's share of a second, so the product is how far to move on this frame.


Check Yourself

Quick quiz

1. What does clock.getDelta() return?

2. Why is cube.rotation.y += 0.01 a problem for a real game?

3. You want a coin to bob up and down smoothly forever. Which loop line does it?

Keep learning

You now know what the animation loop really is, why per-frame motion plays differently on every device, and how one THREE.Clock and a multiply by dt fix it for good. Every loop in the rest of this series starts with that line. Next, your objects stop being plain colors: you paint on a 2D canvas and wrap the result around a cube as a texture.

Part of the Games and Animations with Three.js tutorial series.