RequestAnimationFrame Loop With Delta Time
Read the high-resolution timestamp in each frame callback, clamp long gaps after background tabs, and stop the loop on a frame budget.
Code
// 浏览器 rAF:每帧回调拿到高精度时间戳,适合做基于时间的动画
function createLoop(onFrame) {
let last = 0;
let frames = 0;
function tick(now) {
const delta = last === 0 ? 0 : now - last;
last = now;
// 后台标签页恢复时 delta 可能到秒级:钳制防止逻辑跳变
const clamped = Math.min(delta, 100);
frames++;
onFrame(frames, clamped);
if (frames < 5) requestAnimationFrame(tick);
}
requestAnimationFrame(tick);
return () => frames;
}
// Node 沙箱没有 rAF:浏览器里会真的跑满 5 帧
if (typeof requestAnimationFrame === 'function') {
createLoop((frame, delta) => console.log('frame', frame, 'delta≈', Math.round(delta)));
} else {
console.log('requestAnimationFrame unavailable in this runtime');
console.log('in a browser: 5 frames with clamped deltas, then the loop stops');
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
requestAnimationFrame unavailable in this runtime
in a browser: 5 frames with clamped deltas, then the loop stopsDelta from the callback timestamp
Each tick receives the high-resolution now; delta = now - last gives frame time, with the first frame pinned to 0 because last starts at 0. The loop self-schedules with requestAnimationFrame(tick) until frames reaches 5.
Clamping background gaps
A backgrounded tab stops firing rAF; on return, the raw delta can span seconds. Math.min(delta, 100) caps it so animation logic never sees a multi-second jump — the comment in the code calls out the background-tab case.
Runtime guard
Node has no rAF, so the demo branches: in the browser it prints five frame lines; in a bare runtime it prints the unavailable message plus a description of the expected five-frame clamped run.
Interactive Tools for This Topic
FAQ
- Why is the first frame's delta fixed at 0?
- last starts at 0 and the code special-cases that state, because now - 0 would be the time since the epoch, not a frame gap.
- What breaks without the clamp?
- After a background tab returns, delta can span seconds and time-based animation logic would jump; the 100ms cap keeps each step bounded.
Report a problem with this exampleOpens a pre-filled issue on GitHub.