One coin per requestAnimationFrame makes a faster screen change the economy. Specify thirty coins per second. Ten seconds of uninterrupted simulation should produce roughly 300 at either refresh rate, with at most an unfinished simulation step at the boundary.
Procedure
-
Compute elapsed seconds from successive callback timestamps. On the first call, establish the starting time. Accumulate seconds and simulate whenever a full 1/60-second step is available. Keep fractional production or an integer subunit and round only for display.
-
Render on every callback. The accumulator remainder divided by step size gives an interpolation fraction between previous and current positions. Display the committed balance and avoid awarding production in the draw pass.
-
Reset the last timestamp on foreground return. The example caps one callback’s debt at six steps for visual simulation. Settle offline income separately using a persisted checkpoint. Define which clock owns each interval to prevent double payment.
const step = 1 / 60;
let last, bank = 0, coins = 0;
function frame(now) {
if (last !== undefined) bank += Math.min((now - last) / 1000, 6 * step);
last = now;
while (bank >= step) {
coins += 30 * step;
bank -= step;
}
// Draw from committed state here.
requestAnimationFrame(frame);
}
document.addEventListener("visibilitychange", () => { last = undefined; });
requestAnimationFrame(frame);
Choosing an approach
| Clock | Drives | After a pause |
|---|---|---|
| Display callback | Drawing and feedback | Resume on next callback |
| Fixed tick | Motion and short-lived state | Bound catch-up steps |
| Persisted timestamp | Offline rewards | One capped settlement |
Check the result
Feed 600 synthetic intervals at 60 Hz and 1,440 at 144 Hz to the same update logic. Compare state after ten seconds, allowing one tick of floating-point boundary error. Insert a two-second stall; at most six visual steps should run, with offline production owned by the defined settlement path.
Settle time spent in the background through an offline income checkpoint.
Frequently asked questions
Does every 144 Hz frame need a physics update?
A 60 Hz simulation has display frames without a new tick. Interpolate positions for those frames.
Why is the faster device still losing coins?
Check for rounding every tick. Truncating an award of half a coin on each step removes all production.
References
Related reading
- Save offline income in a Canvas idle game without paying twice on refresh
- A Canvas 2D particle pool with an allocation-free update loop for 144 Hz