Raka's product photo studio has a turntable. It turns at a fixed speed, say one turn every 8 seconds, whether the camera takes 60 or 120 photos a second. That speed belongs to time, not to the number of photos.
Animation in three.js works the same way. You change an object's properties (rotation, position, scale) a little every frame, then render again, and you work out how much from time. In this lesson the Coffee Print Mug from the previous lesson goes on a turntable: it spins by itself, stops smoothly at its print when asked, and hops with a keyframe clip.
The loop: requestAnimationFrame
function animate() {
requestAnimationFrame(animate); // ask to be called again before the next repaint
cube.rotation.x += 0.01;
renderer.render(scene, camera);
}
animate();
requestAnimationFrame(fn)asks the browser to callfnjust before the screen is redrawn: once per refresh, 60 times a second on a 60 Hz screen, 120 times on a 120 Hz screen. When the tab is hidden, the calls stop, so the battery and the GPU rest.- Its callback receives
time, milliseconds since the page opened. Not the time since the previous frame; you work that difference out yourself. setInterval(fn, 16)is not in step with the screen's refresh (some frames double up or are skipped) and keeps running in a hidden tab, only slowed to at most once a second.- three.js has a wrapper:
renderer.setAnimationLoop((time) => { ... })(the Three.js Setup lesson). It does the same, and WebXR needs this one.
Time, not frames: THREE.Timer
rotation.y += 0.01 adds per frame: 0.6 radians a second on a 60 Hz screen, 1.2 on 120 Hz. To make it the same everywhere, multiply a per-second speed by delta, the length of the last frame in seconds.
const timer = new THREE.Timer();
timer.connect(document); // use the Page Visibility API, covered below
const SPEED = 0.8; // radians per second: 1 turn = 2π / 0.8 = 7.85 seconds
renderer.setAnimationLoop((time) => {
timer.update(time); // once per frame, before reading it
const delta = timer.getDelta(); // seconds since the previous frame
turntable.rotation.y += SPEED * delta;
renderer.render(scene, camera);
});
| Screen | delta per frame | Added per frame | Per second |
|---|---|---|---|
| 60 Hz | 0.0167 s | 0.0133 rad | 0.8 rad |
| 120 Hz | 0.0083 s | 0.0067 rad | 0.8 rad |
turntableis aTHREE.Groupthe mug stands on: the loop turns the turntable, and the mug itself is free for the clip to move (the section "Keyframe clips").timer.getElapsed()gives the total seconds since the start, which suits back-and-forth motion:x = Math.sin(t) * 3moves between -3 and 3 (a sine is always between -1 and 1), one swing back and forth every 2π = 6.28 seconds. So a cube withrotation.y += 0.01andposition.x = Math.sin(Date.now() * 0.001) * 3turns on the Y axis while swinging left and right on the X axis.THREE.Clockis deprecated since r183 (in r186 it prints the warningTHREE.Clock: This module has been deprecated. Please use THREE.Timer instead.). Its old trap:getElapsedTime()callsgetDelta()inside, so when both are called in the same frame, the secondgetDelta()is almost 0. Timer doesn't do that:update()once, then read it as often as you like.
Easing: stopping at the print
The "Show the print" button turns the turntable to the nearest multiple of 2π (the print faces the camera, from the Geometry & Material lesson) over 0.8 seconds:
const easeInOutCubic = (p) => (p < 0.5 ? 4 * p * p * p : 1 - Math.pow(-2 * p + 2, 3) / 2);
function showPrint() {
spinning = false;
const to = Math.round(turntable.rotation.y / (2 * Math.PI)) * 2 * Math.PI; // at most half a turn away
turn = { from: turntable.rotation.y, to, t: 0 };
}
// inside the loop:
if (turn) {
turn.t += delta;
const p = Math.min(turn.t / 0.8, 1); // 0 to 1
turntable.rotation.y = turn.from + (turn.to - turn.from) * easeInOutCubic(p);
if (p === 1) turn = null;
}
Easing is a curve that turns progress in time p into progress in motion: at p 0.25 the motion is only at 0.0625, at 0.5 exactly 0.5, at 0.75 already 0.9375. Slow, fast, slow, like someone turning the table by hand. Without easing (p as is), the mug starts and stops dead.
Keyframe clips: AnimationMixer
A keyframe is a value at a given second; three.js fills in the values between. By default it does so in a straight line (linear): halfway in time between two keyframes, the value is halfway too, and a slerped angle also turns at an even rate. The "hop" clip (1.2 seconds) is built by hand, in exactly the shape of a clip that comes from Blender in gltf.animations:
const AXIS_Y = new THREE.Vector3(0, 1, 0);
const q = new THREE.Quaternion();
const hop = new THREE.AnimationClip('hop', 1.2, [
new THREE.NumberKeyframeTrack('.position[y]', [0, 0.6, 1.2], [0, 0.4, 0]),
new THREE.QuaternionKeyframeTrack('.quaternion', [0, 0.4, 0.8, 1.2],
[0, 1, 2, 3].flatMap((i) => q.setFromAxisAngle(AXIS_Y, (i * 2 * Math.PI) / 3).toArray())),
]);
const mixer = new THREE.AnimationMixer(mug);
const action = mixer.clipAction(hop).setLoop(THREE.LoopOnce);
hopButton.addEventListener('click', () => action.reset().play());
// inside the loop, after working out delta:
mixer.update(delta);
- A track's name points at a property of
mug(the mixer's root):'.position[y]'only the y component,'.quaternion'the whole rotation.'handle.quaternion'would point at a child namedhandle. - Rotations in a clip are stored as quaternions (4 numbers for one direction) and filled in with slerp, which always takes the shortest way. A 0° and a 360° quaternion point the same way, so a clip with only those two keyframes leaves the mug still. One full turn needs a keyframe every 120°.
LoopOnceplays once; after 1.2 seconds the mug is back where it started.reset().play()starts from second 0 again. Withoutmixer.update(delta)every frame, the clip doesn't move at all.- The loop owns
turntable.rotation, the mixer ownsmug.quaternion. If both change the same object, the last one overwrites the other.
Hidden tabs and reduced motion
While the tab is hidden, requestAnimationFrame stops. Say Raka switches to another tab for 10 seconds, then comes back. The first frame arrives 10 seconds after the last one, so if the loop uses timer.getDelta() without connect, the delta is 10 seconds and the turntable, turning 0.8 radians per second, jumps 0.8 × 10 = 8 radians (1.27 turns) in one frame. There are two cures:
timer.connect(document): while the tab is hidden delta is 0, and on return the timer starts counting from then. The turntable carries on from where it was.Math.min(timer.getDelta(), 0.1): delta is capped at 0.1 seconds, the trick from the Canvas Animation lesson.
For visitors whose system asks for reduced motion (vertigo, motion sickness), don't spin by yourself:
const reducedMotion = matchMedia('(prefers-reduced-motion: reduce)');
let spinning = !reducedMotion.matches;
reducedMotion.addEventListener('change', () => { spinning = !reducedMotion.matches; });
"Show the print" then moves at once with no animation, and the hop clip is skipped.
Don't make new objects inside the loop
Every new THREE.Vector3() or .clone() in the loop becomes garbage that the garbage collector (GC) cleans up later, and meanwhile JavaScript pauses for a moment. Measured in Chrome (a laptop, 120 fps, 8 seconds, 1,000 steam particles): reusing one vector, 1 GC; new THREE.Vector3() per particle, 7; position.clone() per particle, 34, 6.6 ms in all. On the laptop each pause is only about 0.3 ms; on a phone with a 4 times slower CPU, an estimated 1.3 ms, while a 120 Hz frame is only 8.3 ms. Make temporary objects once, outside the loop:
const temp = new THREE.Vector3(); // once only
for (const p of particles) p.position.add(temp.set(0, 0.3 * delta, 0));
⚠️ A mug that turns too fast, stands still or suddenly jumps
- Adding a fixed number per frame (
+= 0.01): the mug turns twice as fast on a 120 Hz screen. Multiply bydelta. getElapsedTime()thengetDelta()on THREE.Clock: delta is almost 0, the object barely moves. UseTHREE.Timer.- No
timer.connect(document)and no cap on delta: the mug jumps after a hidden tab. - Only 0° and 360° quaternion keyframes: the mug stays still; add a keyframe every 120°.
- Forgetting
mixer.update(delta): the clip is playing but nothing moves.
TL;DR: Animation = change properties every frame, then render. requestAnimationFrame (or renderer.setAnimationLoop) runs once per screen refresh and stops in a hidden tab; its callback receives time, not a delta. Work motion out from time: THREE.Timer (update(time), getDelta(), getElapsed()), not THREE.Clock, deprecated since r183; += SPEED * delta, Math.sin(t) * 3 to swing between -3 and 3. Easing (easeInOutCubic) makes starts and stops smooth. Keyframe clips: AnimationClip + NumberKeyframeTrack / QuaternionKeyframeTrack, AnimationMixer, clipAction(...).play(), mixer.update(delta). timer.connect(document) stops the jump after a hidden tab, prefers-reduced-motion turns the auto-spin off, and temporary objects are made once, outside the loop.
⚡ A loop in step with the screen
Write:
function animate() {
requestAnimationFrame(animate); // ask to be called again before the next repaint
cube.rotation.x += 0.01;
renderer.render(scene, camera);
}
animate();
Guess first: the tab is hidden. Which keeps running, setInterval(fn, 16) or requestAnimationFrame?
setInterval, only slowed to at most once a second. requestAnimationFrame stops, so the battery and the GPU rest.
Meaning: requestAnimationFrame is in step with the screen's refresh: once per refresh, 60 times a second on a 60 Hz screen, 120 times on a 120 Hz one.
⚡ Time, not frames
Write:
timer.update(time); // once per frame, before reading it
const delta = timer.getDelta(); // seconds since the previous frame
turntable.rotation.y += SPEED * delta;
Meaning: += 0.01 per frame is twice as fast on a 120 Hz screen. A per-second speed times delta makes the turntable turn just as fast on any screen.
⚡ Easing and clips
Meaning: Easing like easeInOutCubic makes the motion slow, fast, then slow, so the mug doesn't start and stop dead. A keyframe clip is played by an AnimationMixer, and without mixer.update(delta) every frame, the clip doesn't move at all.