skip to content

Game Loop and Timestep

How the loop advances simulation time: fixed vs variable timestep, the accumulator and render-state interpolation. Interviewers start here because one timestep answer explains jitter and blow-ups.

on this pageshow

explore

questions

6

What does a game loop do on each iteration, and why is per-frame movement scaled by the elapsed frame time?

level: juniorimportance: must knowfreq 72%

answer

  1. input, update, render, repeat
  2. frames are not equally long
  3. units per second, not per frame
  4. multiply speed by elapsed seconds

basics

~20 s

A game loop repeats input handling, a simulation update and rendering for as long as the game runs. Frame lengths vary across machines and moments, so movement is written per second and multiplied by the elapsed frame time.

solid answer

~50 s

A game loop is the outer loop of a game: each iteration reads input, advances the simulation by some amount of time, and renders the result, then starts again. Nothing guarantees that iterations take the same wall-clock time; a faster machine or a lighter scene runs more of them per second. If code moves an object by a fixed amount per iteration, its speed depends on the frame rate, so the same enemy crosses the room twice as fast at 120 frames per second as at 60. The fix is to measure the elapsed time since the previous iteration, usually called `dt` or delta time, express rates per second, and write `position = position + velocity * dt`. That makes linear motion frame-rate independent; for motion that changes over time, such as acceleration or a jump, step size still matters, which is why many games also run physics on a fixed step.

code

pseudocode · 8 lines
pseudocode
previous = monotonicClockSeconds()
while running:
    now = monotonicClockSeconds()
    dt = now - previous
    previous = now
    processInput()
    update(dt)          // every rate is per second, multiplied by dt
    render()

go deeper

for a junior

Name the three stages of each iteration and show that movement is written in units per second and multiplied by the elapsed time since the previous frame.

for a middle

Explain why delta time fixes constant-rate motion exactly but not accelerating motion, and why a long frame needs its delta time clamped.

for a senior

Connect delta time to the decision of what runs on a variable step and what runs on a fixed step, and how the loop measures time reliably.

for a principal

Be ready to justify which systems a team allows on a variable step, since that rule decides how reproducible gameplay is across hardware.

## What a game loop is A **game loop** is the outermost loop of a running game. Unlike an event-driven desktop application that sleeps until the user clicks something, a game has to keep the world moving even when the player does nothing: enemies walk, timers count down, particles drift. So the program runs a loop that, on every **iteration** (one pass through the loop, usually producing one rendered **frame**), does roughly the same three jobs: 1. **Process input** - poll the keyboard, mouse, gamepad or touch state and turn it into intentions such as jump or move left. 2. **Update the simulation** - advance every moving thing in the world by some amount of simulated time: movement, timers, animation clocks, physics, AI. 3. **Render** - draw the current state of the world and hand the image to the display. Then it measures how long that took and goes round again. Real engines add more stages (audio, networking, streaming, deferred work), but this input, update, render cycle is the skeleton every engine shares. ## Why frames are not all the same length The time one iteration takes is not constant. It depends on: - the **hardware** - a fast desktop may finish an iteration in 4 ms, an older laptop in 30 ms; - the **scene** - an empty corridor is cheaper to simulate and draw than a battle with hundreds of effects; - **background work** - the operating system, a loading thread or a garbage collection can steal time; - **display synchronisation** - when the loop waits for the screen's refresh, the frame time snaps to the refresh interval. So the number of iterations per second, the **frame rate**, varies between machines and from moment to moment on one machine. ## Per-frame movement and its bug The naive way to move an object is a fixed amount per iteration: ```pseudocode // frame-rate dependent: speed is 0.05 units per FRAME position = position + 0.05 ``` At 60 frames per second that is 3 units per second; at 120 it is 6; at 30 it is 1.5. The game literally runs at a different speed on different machines. Classic arcade titles could do this because the hardware was fixed, but on PCs, consoles with performance modes and phones it is a bug. ## Delta time: rates per second The fix is to measure the **elapsed time** since the previous iteration, commonly called `dt` or **delta time**, in seconds, and write every rate per second: ```pseudocode speed = 3.0 // units per SECOND position = position + speed * dt // dt = seconds since last frame ``` At 60 frames per second `dt` is about 0.0167 s, so each frame moves 0.05 units; at 120 frames per second `dt` is about 0.0083 s and each frame moves 0.025 units. Either way the enemy covers 3 units per second. The same rule applies to anything that changes over time: | Quantity | Per-frame (wrong) | Per-second with delta time | |---|---|---| | Movement | `x += 0.05` | `x += speed * dt` | | Cooldown timer | `timer -= 1` | `timer -= dt` | | Rotation | `angle += 2` | `angle += turnRate * dt` | | Velocity under gravity | `v -= 0.16` | `v -= g * dt` | ## Where delta time is not enough Scaling by `dt` makes **constant-rate** changes frame-rate independent exactly. It does not make everything identical at every frame rate: - **Accelerating motion** (gravity, springs, drag) is advanced in discrete steps, and the result of a discrete step depends on how long it is, so a jump can reach a slightly different height at 30 and at 144 frames per second. - **Very long frames** after a hitch produce a huge `dt`, which can push an object through a wall in one jump; engines clamp `dt` to a maximum for this reason. - **Order-dependent logic** such as checking a trigger once per frame sees different intermediate states at different frame rates, so a fast-moving object may be inside a trigger zone on one machine and past it on another. These limits are why many engines run the simulation, or at least physics, on a **fixed timestep** and leave the variable `dt` to things like camera smoothing, UI and visual effects. ## How the loop measures time The loop reads a **monotonic high-resolution clock** (one that never jumps backwards when the wall clock is adjusted) at the start of each iteration and subtracts the previous reading. Using a coarse or adjustable clock gives zero or negative `dt` values and visible stutter.

  • Why read a monotonic clock rather than the system wall clock for delta time?
    The wall clock can be adjusted by time synchronisation, daylight-saving changes or the user, so the difference between two readings can be zero, huge or negative. A monotonic clock only moves forward at a steady rate, which is what an elapsed-time measurement needs. It should also have sub-millisecond resolution, or short frames read as zero.
  • What should a variable-step loop do when one frame takes two seconds because the window was dragged or the game was paused in a debugger?
    Clamp delta time to a maximum, such as a tenth or a quarter of a second, before passing it to the update. Otherwise objects jump across the level in one update and can pass through walls or skip triggers. The game appears to pause briefly instead, which players accept far more readily than teleporting objects.

A delta-time update is like a car's odometer: it adds speed times elapsed time, so the distance covered is the same whether you glance at it ten times a minute or once.

  • Moving objects a fixed amount per frame and calling it fine on fast PCs
  • Believing delta time makes every physics result identical at any frame rate
  • Reading the adjustable wall clock to measure frame time
  • Assuming every frame takes exactly one sixtieth of a second
  • Never clamping delta time after a long pause or hitch
open as a page

Why can a character's jump height differ at 30 and 144 frames per second even when every update is scaled by delta time?

level: middleimportance: must knowfreq 66%

basics

~20 s

Accelerating motion advances in discrete steps whose result usually depends on their length, so each frame rate gives a different trajectory and apex. A fixed simulation timestep gives every machine identical steps and the same height.

open as a page

How does an accumulator run a fixed simulation step under a variable frame rate, and why interpolate rendered state with the leftover fraction?

level: seniorimportance: must knowfreq 64%

basics

~20 s

An accumulator banks each frame's real elapsed time and runs whole fixed steps while it holds at least one. The leftover fraction, divided by the step, blends the previous and current simulation states so motion looks smooth at any display rate.

open as a page

How do vsync and double or triple swapchain buffering trade tearing and smooth frame pacing against input latency in a game loop?

level: middleimportance: should knowfreq 46%

basics

~20 s

Vsync waits for the display's refresh boundary so images never tear, but a missed deadline costs a whole extra refresh. More swapchain buffers keep the rate up, but queued images add input latency and uneven pacing judders.

open as a page

After a long hitch, a fixed-step game loop falls further behind every frame and never recovers; what is this spiral of death and how do you prevent it?

level: seniorimportance: should knowfreq 52%

basics

~20 s

The spiral of death is a fixed-step loop whose catch-up steps cost more real time than they simulate, so each frame owes more steps. Clamping frame time, capping steps per frame and cheap steps prevent it.

open as a page

How would you choose the fixed tick rate for a dedicated game server, and what does raising it cost the server, the network and the players' clients?

level: principalimportance: should knowfreq 38%

basics

~20 s

Choose the lowest fixed tick rate that the game's pace and precision need, measured against per-tick cost at peak load. Raising it multiplies server CPU and often bandwidth, shrinks the time each tick may take, and changes tuning that clients share.

open as a page