This module implements a fixed timestep game loop using requestAnimationFrame, with support for:
delta timealpha valueIt is commonly used in games and simulations where stable physics updates are required regardless of frame rate fluctuations.
Creation → Start → Update/Render Loop → Stop
createLoopstartLooptick calls manage update and render phasesstopLoopLoopStateRepresents the internal state of the loop.
lastTime: number
Timestamp of the last frame (in milliseconds)
accumulator: number
Accumulated time not yet processed by fixed updates
fixedDelta: number
Fixed timestep duration in seconds (default: 1/60)
update(dt: number): void
Function called at fixed intervals with dt = fixedDelta
render(alpha: number): void
Render function called once per frame with interpolation factor
running: boolean
Whether the loop is currently active
frameId: number | null
Current requestAnimationFrame ID
createLoop(update, render, fixedDelta?)Creates and returns a new loop state.
Parameters
update(dt: number) – fixed-step update functionrender(alpha: number) – interpolated render functionfixedDelta?: number – timestep in seconds (default: 1/60)Returns
LoopStatestartLoop(state)Starts the animation loop if it is not already running.
Behavior
running = truerequestAnimationFrame callbackstopLoop(state)Stops the loop and cancels pending animation frames.
Behavior
running = falsecancelAnimationFrameframeIdtick(state, time)Core loop function executed every animation frame.
state.running is falselastTime = timedelta = (time - lastTime) / 1000
0.25s to avoid spiral-of-death on lag spikesstate.accumulatorstate.update(fixedDelta) as many times as needed:
while (accumulator >= fixedDelta)
alpha = accumulator / fixedDelta
state.render(alpha)requestAnimationFrameconst loop = createLoop(
(dt) => {
// physics / game logic update
position += velocity * dt;
},
(alpha) => {
// interpolation for smooth rendering
renderSprite(position + velocity * alpha);
}
);
startLoop(loop);
// later...
stopLoop(loop);
requestAnimationFrame — browser API used for frame scheduling