Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is HTML5 localStorage asynchronous?

Tags:

html

People also ask

Are localStorage methods async?

localStorage is a synchronous API. You could defer the setItem method execution with the Promise object, giving them an asynchronous behaviour: const asyncLocalStorage = { setItem: function (key, value) { return Promise.

Is sessionStorage setItem synchronous?

To create a key-value pair inside the sessionStorage object, you can use the setItem method, similar to the localStorage object. Just like localStorage , sessionStorage is also a synchronous API, so you can be sure that you'll immediately have access to whatever values you're storing.

What is HTML5 localStorage?

HTML5 local storage is a component of the Web storage application programming interface. It is a method by which Web pages locally store named key/value pairs inside a client's Web browser.

Which type of HTML5 storage is best recommended?

Local storage is more secure, and large amounts of data can be stored locally, without affecting website performance. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.


Nope, all localStorage calls are synchronous.


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.