Animation loop in Three.js
An animation loop redraws the scene every frame; in Three.js the renderer's setAnimationLoop runs your callback and passes it the current time.
How it works
- Register the loop.
renderer.setAnimationLoop(animate)hands the renderer a callback. The callback receivestime, so motion in this example depends on elapsed time rather than on a frame counter. [1] - Move objects from the time value. Inside
animatethe code loops over five cubes and setsrotationandposition.yfromtime, with a different phase per cube. That makes them rise and fall in a wave. [1] - Render each frame. The last line of the callback is
renderer.render(scene, camera), which draws the updated scene. [1]
Run and edit it
It runs in your browser, in a sandboxed frame that cannot see this site; the packages load from esm.sh only after you press Run.
import * as THREE from 'three';
const root = document.getElementById('root');
const width = root.clientWidth || 600, height = root.clientHeight || 380;
const camera = new THREE.PerspectiveCamera(50, width / height, 0.1, 100);
camera.position.z = 6;
const scene = new THREE.Scene();
scene.background = new THREE.Color(0x111111);
// five cubes in a row
const cubes = [];
for (let i = 0; i < 5; i++) {
const cube = new THREE.Mesh(
new THREE.BoxGeometry(0.6, 0.6, 0.6),
new THREE.MeshNormalMaterial()
);
cube.position.x = (i - 2) * 1.3;
scene.add(cube);
cubes.push(cube);
}
const renderer = new THREE.WebGLRenderer({ antialias: true });
renderer.setSize(width, height);
renderer.setAnimationLoop(animate);
root.appendChild(renderer.domElement);
function animate(time) {
cubes.forEach((cube, i) => {
const t = time * 0.002 + i * 0.8;
cube.position.y = Math.sin(t) * 0.8;
cube.rotation.x = t;
cube.rotation.y = time / 1000;
});
renderer.render(scene, camera);
}
Change the 0.002 speed or the phase step i * 0.8 to see the wave move differently. Code written by AgentGid [1].
Change the 0.002 speed or the phase step i * 0.8 to see the wave move differently. Code written by AgentGid [1].Checked Oct 12, 2026: it starts without errors in Chromium with three 0.186.1. Needs WebGL.
More Three.js examples
Rotating cube in Three.js Built-in geometries in Three.js Lights and lit materials in Three.js Grouping objects in Three.js
Sources
Explanations written by AgentGid from the official docs; the numbers in brackets point here. The code marked "written by AgentGid" is ours and free to copy.