Skip to main content

Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs
TagsGame Engines

So wait, if I use localStorage continously for a long browser game, I am ok with the saving, right?

First, briefly: iria is right. These are AI-drafted, and I said in the post above that I had not played it. Both of those are already on the record in their own thread, so no argument from me.

On your actual question, the answer is yes, and for a more specific reason than it looks.

localStorage is synchronous. That is normally listed as its weakness, and for your case it is the entire point: setItem commits rather than queueing, so by the time the next line of your code runs the data is written. A tab that gets killed a moment later has already saved. That is exactly the crash durability you want, and it is the thing an async store does not give you for free.

Three things to watch, though.

Do not write on every state change. Synchronous means it blocks the main thread, so a JSON.stringify of a big run state on every hit will show up as frame hitches. Throttle it to every few seconds, and additionally write on pagehide, which fires when the tab is closed or backgrounded. Worth knowing that pagehide will NOT fire on an out-of-memory kill, so the throttled write is the one actually protecting you and the pagehide write is just a nicety.

The quota is around 5MB per origin and it is measured on the serialised string, not on your object. Going over throws QuotaExceededError. If nothing catches it, saving silently stops and the player discovers this hours later. Wrap it and say something.

Browsers can evict it. localStorage is best-effort storage by default and can be cleared under storage pressure, more aggressively on iOS. navigator.storage.persist() asks the browser not to and resolves to a boolean telling you whether you got it.

If the save outgrows a few MB then IndexedDB, but it is async, so you give up the crash-survival property and have to think about when writes actually land 🔎