IntelInlet
Studio journal
Canvas game engineering / / 2 min read

Save offline income in a Canvas idle game without paying twice on refresh

Commit balance, rate and settlement time as one snapshot and test clock changes, sleep and concurrent tabs.

A player leaves with 120 coins and a rate of two per second. Ten minutes later the award is 1,200 and the balance is 1,320. If the balance is saved first and the timestamp much later, a refresh can pay for the same ten minutes twice.

Procedure

  1. Define version, coins, rate and settledAt in the snapshot. Validate finite values, types and timestamp units on load. Migrate older formats explicitly. Preserve an unreadable save for recovery before replacing progress.

  2. Convert elapsed milliseconds to seconds and clamp between zero and the product’s offline cap. Apply the old rate to the old interval, then apply an upgrade. Serialize the new balance and timestamp together in one setItem call. If storage fails, keep the in-memory state and show the save failure.

  3. Save after purchases, on transition to the background and at reasonable periodic checkpoints. Synchronous localStorage writes on every frame consume main-thread time. A single-key snapshot cannot arbitrate concurrent tabs. Enforce one active session or use a versioned IndexedDB read/update transaction.

function settle(save, now, capSeconds = 8 * 3600) {
  const seconds = Math.max(0, Math.min(capSeconds, (now - save.settledAt) / 1000));
  return {
    ...save,
    coins: save.coins + save.rate * seconds,
    settledAt: Math.max(save.settledAt, now)
  };
}

Choosing an approach

Scenario Expected Inspect
Ten minutes away 120 to 1,320 Units and previous rate
Clock moves backwards No award for this interval Clock anomaly policy
Immediate second reload No second ten-minute award Atomic snapshot fields

Check the result

Pass an explicit now into settlement tests. Supply the departure time, departure plus 600,000 ms, the identical timestamp and a time beyond the cap. Test simultaneous upgrades in two tabs for stale overwrites. A local wall clock cannot establish trustworthy competitive rankings.

Check active production against the same rules with the fixed-step rate test.

Frequently asked questions

Can I save only on tab close?

A closing event may not finish. Use purchase and background checkpoints plus periodic saves to bound lost progress.

Should the new upgraded rate apply during absence?

Settle the past interval with the rules recorded at departure, then apply the upgrade. Define a migration policy for economy changes across versions.

References

Related reading

Chibi arcade ↗