Home > Web Front-end > JS Tutorial > body text

How to Manage Data Expiration in HTML5 Local Storage?

Patricia Arquette
Release: 2024-10-28 04:09:01
Original
490 people have browsed it

 How to Manage Data Expiration in HTML5 Local Storage?

Storing Data Expiration in HTML5 Local Storage

Data stored in HTML5's Local Storage component (part of DOM Storage) persists indefinitely until explicitly cleared or overwritten. However, the ability to set an expiration time for cached data is not natively provided.

Solution to Managing Expiration

One approach is to store a timestamp alongside the data itself. For instance:

<code class="javascript">var object = { value: "value", timestamp: new Date().getTime() };
localStorage.setItem("key", JSON.stringify(object));</code>
Copy after login

Upon retrieval, you can parse the stored object, extract the timestamp, and compare it to the current time. If the expiration period has passed, you can update the data accordingly.

<code class="javascript">var object = JSON.parse(localStorage.getItem("key"));
var dateString = object.timestamp;
var now = new Date().getTime().toString();

compareTime(dateString, now); // Implementation required</code>
Copy after login

Alternatively, you can use a third-party library such as localstorage-slim.js, which provides an API for setting expiration times for Local Storage data.

The above is the detailed content of How to Manage Data Expiration in HTML5 Local Storage?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!