5 min read
PID control for real-time UIs: why a spring lags a moving target
A UI spring is a PD controller. Against a target that keeps moving, such as the time axis of a live chart, it settles with a constant lag of c·v/k. The control-theory reason, two fixes, and how to step the simulation independently of frame rate.
Spring animations are the default for interactive motion, and for a target that jumps from one value to another they are the right tool. A real-time trading UI has a different kind of target: one that never stops. The viewport of a live chart follows time itself, a depth ladder recentres on a drifting mid, a scale follows a trending price. Against those, a spring is always behind by a fixed distance, and no amount of tuning the usual two parameters removes it.
The explanation is standard control theory, and it leads directly to the fix.
A spring is a PD controller
A UI spring integrates this equation every frame:
acceleration = k · (target − x) − c · velocitySet that beside a PID controller acting on the error e = target − x:
output = Kp · e + Ki · ∫e dt + Kd · de/dtStiffness k is the proportional gain. Damping c is a derivative term, with one difference: it acts on the velocity of the element, not on the rate of change of the error. There is no integral term. Every spring library ships a PD controller, with the derivative taken on the measurement.
For a step change in the target this is ideal. The error goes to zero, and choosing c = 2·√k (critical damping, for unit mass) gets there fastest without overshoot. Overshoot is charming on a toggle and wrong on anything showing a price.
The steady-state lag
Now let the target move at constant velocity v: a ramp. In steady state the element moves at v too, so its acceleration is zero:
0 = k · e − c · v ⇒ e = c · v / kThe element trails the target by c·v/k for as long as the target keeps moving. Stiffer springs shrink the lag and bring back overshoot and jitter; they never make it zero.
The time axis of a streaming chart is exactly this input. If "now" should sit at the right edge and the viewport follows it with a spring, the newest data is permanently drawn c·v/k pixels past where the viewport is looking.
A simulation with k = 170, c = 26 (just under critical damping) and a target moving at 400 px/s:
type Gains = { k: number; c: number; ki?: number; ff?: number };
// Follow a target moving at constant velocity; report the steady-state lag.
function follow({ k, c, ki = 0, ff = 0 }: Gains, targetVelocity: number) {
const dt = 1 / 240;
let x = 0;
let v = 0;
let integral = 0;
let target = 0;
for (let t = 0; t < 6; t += dt) {
const error = target - x;
integral += error * dt;
const a = k * error + ki * integral - c * (v - ff * targetVelocity);
v += a * dt; // semi-implicit Euler: velocity first, then position
x += v * dt;
target += targetVelocity * dt;
}
return target - x;
}
follow({ k: 170, c: 26 }, 400); // 61.18 (c·v/k = 61.18)
follow({ k: 170, c: 26, ki: 400 }, 400); // 0.00
follow({ k: 170, c: 26, ff: 1 }, 400); // 0.00Sixty-one pixels of lag, matching the formula, and two ways to remove it.
The same loop, live. The view rides on the target, the way a chart viewport rides on the current time, so the gap you see is the lag. Change the speed and the gap follows c·v/k; add the integral term or feedforward and it closes. "Jump target" applies a step, which is where the integral term shows its overshoot and feedforward does not.
This interactive figure needs JavaScript.
Fix one: the integral term
Adding Ki · ∫e dt is the textbook answer. Any persistent error accumulates in the integral until the output is large enough to cancel it, so the lag goes to zero without knowing anything about the target's speed.
It comes with the two classic costs. The integral makes the response to a step overshoot, because the error accumulated on the way in has to be unwound on the other side. And it winds up: if the element is held at a limit, or the tab is in the background while the target moves on, the integral grows without bound and the element shoots past when released. Any implementation needs anti-windup: clamp the integral, and reset it on discontinuities such as a symbol change, a jump to a new time range, or the page becoming visible again.
Fix two: feedforward
When the target's velocity is known, there is a better option. Damp the difference between the element's velocity and the target's, not the element's absolute velocity:
acceleration = k · (target − x) − c · (velocity − targetVelocity)In steady state the damping term vanishes and the error is zero, with no integral, no overshoot on steps and nothing to wind up. For a time axis the target velocity is known exactly: one second per second, times the zoom. For a price-following scale it can be estimated from the last few updates.
Feedforward is the better default for UI work. Keep the integral term for the case it is meant for: an offset whose cause cannot be measured.
Stepping the simulation
All of this assumes the controller runs at a fixed rate. A display does not provide one. Frames arrive at 60, 120 or 144 Hz depending on the monitor, a blotter under load drops frames, and a background tab is throttled to a crawl. Feeding the raw frame time into the integrator makes the animation depend on the machine, and beyond a certain step size it becomes unstable. With the gains above:
| Step | Result |
|---|---|
| 1/240 s to 1/20 s | Converges to the target |
| 80 ms | Diverges (10¹⁶ px after 60 steps) |
| 100 ms | Diverges (10²⁸ px after 60 steps) |
A step of 80 ms is one long garbage collection or a single frame after the tab regains focus. The fix is to run the controller on a fixed timestep and let the frame loop consume whole steps:
const STEP = 1 / 240; // seconds
const MAX_FRAME = 0.1; // after a stall, catch up at most this much
let last = performance.now();
let accumulator = 0;
function frame(now: number) {
accumulator += Math.min((now - last) / 1000, MAX_FRAME);
last = now;
while (accumulator >= STEP) {
step(STEP); // one controller update, as in follow() above
accumulator -= STEP;
}
render();
requestAnimationFrame(frame);
}
requestAnimationFrame(frame);The derivative term has one more practical problem: it amplifies noise. Differentiating the error means differentiating the target, and a target driven by ticks is a staircase. Taking the derivative on the measurement, which is what a spring's damping already does, avoids the kick on every update.
What to animate on a trading screen
A controller smooths motion by showing intermediate values. That is acceptable for a viewport and not for data.
- Animate where the user is looking: scroll position, axis range, ladder centring, panel sizes.
- Never animate what the data says. A price that tweens from 101.2 to 101.5 displays values that never traded. Numbers change in a single frame; draw attention with a flash on the cell, not with motion of the digits.
- Snap on discontinuities. A symbol change or a jump to a different time range is a new scene. Easing across it implies continuity that is not there, so set position, zero velocity and reset the integral.
- Honour
prefers-reduced-motionby snapping, which is also the correct behaviour when the machine cannot hold frame rate.
The useful part of PID for interface work is the vocabulary more than the controller. Knowing that a spring is a PD loop explains the lag, predicts its size, and shows that the cure is knowledge of the target's velocity and not a stiffer spring.