Is HTML5 localStorage asynchronous?

Html

Html Problem Overview


Is the setItem(key,value) function asynchronous?

localStorage.setItem("key",someText);

Html Solutions


Solution 1 - Html

Nope, all localStorage calls are synchronous.

Solution 2 - Html

Actually. web storage is no longer part of the HTML5 core standard, it's been split off.

The relevant (draft) specification can be found here and the one thing you'll notice is that it doesn't mention synchronous or asynchronous anywhere.

However, analysis of the text would suggest that it must be synchronous (my bold):

> The setItem(key, value) method must first check if a key/value pair with the given key already exists in the list associated with the object. > > If it does not, then a new key/value pair must be added to the list, with the given key and with its value set to value. > > If the given key does exist in the list, and its value is not equal to value, then it must have its value updated to value. If its previous value is equal to value, then the method must do nothing.

In standards, words like must, shall and may carry very specific meanings. That fact that it's talking about what the method must do means that the method itself must do it, not defer it to some later time.

This also defers to common sense as well. If the setItem were asynchronous, it would be possible to set an item to a specific value then immediately retrieve it, getting its previous value.


There is a note at the bottom of the storage interface section which hints at the possibility of asynchronous behaviour:

> This specification does not require that the above methods wait until the data has been physically written to disk. Only consistency in what different scripts accessing the same underlying list of key/value pairs see is required.

However, that's only in terms of what's written to long-term storage. The last sentence mandates that scripts accessing the same storage object are required to see things synchronously.

Solution 3 - Html

localStorage.getItem() and localStorage.setItem() both are synchronous.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionjas7View Question on Stackoverflow
Solution 1 - HtmlRyan NigroView Answer on Stackoverflow
Solution 2 - HtmlpaxdiabloView Answer on Stackoverflow
Solution 3 - HtmlPrabha ShankerView Answer on Stackoverflow