According to W3C Web Storage Recommendation (see here), §4.5 "Threads":
Because of the use of the storage mutex, multiple browsing contexts will be able to access the local storage areas simultaneously in such a manner that scripts cannot detect any concurrent script execution.
Thus, the length attribute of a Storage object, and the value of the various properties of that object, cannot change while a script is executing, other than in a way that is predictable by the script itself.
Which means to me is that the mutex is placed on first access (read or write) of the script to localStorage
and kept until this event loop entry execution returns. Effectively, we have exclusive access to the localStorage
for the duration of the execution chain.
I would imagine, if await/async
are used, it would break the execution chain, and make the code executed across multiple event loop entries, thus breaking this contract. Even though the source code block looks monolithic. Beware.
The answer to the question is: Yes, the code in question would behave correctly, providing the browser keeps to the W3C recommendation. This is despite the fact that the "test" if(!localStorage.generator)
and the "increment" localStorage.generator++
are in the different lines and in most other execution environments are not guaranteed to execute atomically.