timer.connect( document )
const timer = new THREE.Timer();
timer.connect( document );是什么意思
这两行代码是 three.js 里 THREE.Timer 的用法,用来创建一个与页面时间同步的计时器,常用于动画或时间控制。
我们一行一行解释 👇
第一行
const timer = new THREE.Timer();这行代码是:
👉 创建一个 Three.js 计时器对象
它的作用类似于:
clock.getDelta()(以前常用)performance.now()requestAnimationFrame时间计算
但 THREE.Timer 是更现代的时间系统(WebGPU 示例中常用)
例如:
timer.getDelta() // 获取两帧之间的时间timer.getElapsed() // 获取总运行时间第二行
timer.connect( document );这行代码的意思是:
👉 把 timer 连接到 document 的生命周期
也就是:
当页面发生这些情况时:
- 页面隐藏(切后台)
- 页面恢复(切回来)
- 页面暂停
Timer 会自动:
- 暂停计时
- 恢复计时
- 防止时间跳变
为什么需要 connect(document)?
如果不连接:
比如:
你切换浏览器标签页 10 秒
回来后:
timer.getDelta()可能会变成:
10 秒这会导致:
- 动画突然跳跃
- 物理模拟爆炸
- 粒子系统异常
而:
timer.connect(document)会让 timer:
✅ 自动暂停
✅ 自动恢复
✅ 时间连续
实际动画示例
const timer = new THREE.Timer();
timer.connect(document);
function animate() {
const delta = timer.getDelta();
cube.rotation.y += delta;
renderer.render(scene, camera);
}
这样动画就会:
- 切换标签页不会爆炸
- 时间不会跳变
- 更稳定
THREE.Timer vs THREE.Clock
旧写法:
const clock = new THREE.Clock();
clock.getDelta();
新写法(WebGPU 推荐):
const timer = new THREE.Timer();
timer.connect(document);
timer.getDelta();
👉 Timer 更现代,更稳定,更适合 WebGPU
总结
const timer = new THREE.Timer();
创建计时器
timer.connect(document);
让计时器和页面生命周期同步(防止时间跳变)
案例:
three.js webgpu - animation retargeting

浙公网安备 33010602011771号