Home Web Front-end HTML Tutorial Manage and set the validity period of localstorage

Manage and set the validity period of localstorage

Jan 11, 2024 pm 04:37 PM
learn Expiration localstorage management

Manage and set the validity period of localstorage

Understanding the expiration time of localstorage and how to manage it requires specific code examples

In modern front-end development, local storage is a very important concept. Among them, localstorage is the most commonly used local storage method. It saves the data in the browser's local environment for later use. However, when using localstorage, we also need to consider the expiration time of the data and how to manage this data.

Localstorage does not have a native expiration time setting mechanism. By default, data stored in localstorage will remain in the user's browser until the user manually clears it or the browser cache is cleared. However, in many practical applications, we usually need to set the expiration time of data to ensure the timeliness of the data.

When dealing with the expiration time of localstorage data, the common method is to manage it by adding a timestamp (timestamp) or an expiration timestamp (expiration timestamp). A timestamp is a number that represents the current time, usually expressed as a Unix timestamp, which is the number of seconds that have elapsed since 00:00:00 on January 1, 1970. By comparing the current time with the stored timestamp, we can determine whether the data has expired.

The following is a sample code that shows how to set and manage the expiration time of localstorage data:

// 设置localstorage数据,并添加过期时间
function setLocalStorageData(key, value, expirationHours) {
  const expirationMS = expirationHours * 60 * 60 * 1000; // 将小时转换为毫秒
  const expirationTime = Date.now() + expirationMS; // 计算过期时间戳
  const data = {
    value: value,
    expirationTime: expirationTime
  };
  localStorage.setItem(key, JSON.stringify(data));
}

// 获取localstorage数据,并检查是否过期
function getLocalStorageData(key) {
  const data = JSON.parse(localStorage.getItem(key));
  if (data && data.expirationTime && data.expirationTime > Date.now()) {
    return data.value;
  }
  return null; // 数据已过期或不存在时返回null
}

// 示例用法
setLocalStorageData('username', 'JohnDoe', 24); // 设置一个过期时间为24小时的数据
const username = getLocalStorageData('username'); // 获取数据
console.log(username); // 输出 "JohnDoe"

setTimeout(() => {
  const expiredUsername = getLocalStorageData('username'); // 延迟后再次获取数据
  console.log(expiredUsername); // 输出 null,数据已过期
}, 25 * 60 * 60 * 1000); // 延迟25小时
Copy after login

In the above sample code, we use the setLocalStorageData method to set localstorage data , and add an expiration time. In this method, we first convert the expired hours to milliseconds and get the current timestamp through the Date.now() method. Then, we save the data and the calculated expiration timestamp in an object, and serialize the object into a string through the JSON.stringify method and store it in localstorage.

At the same time, we also wrote the getLocalStorageData method to obtain localstorage data and check whether the data has expired. In this method, we first parse the localstorage data into an object through the JSON.parse method. We then check if there is an expiration timestamp in the parsed object, and if the expiration timestamp is greater than the current timestamp. If the data has not expired, the value of the data is returned; otherwise, null is returned.

The last part of the example shows how to use these two methods. We first use the setLocalStorageData method to set a data with an expiration time of 24 hours. Then, get this data through the getLocalStorageData method and print the result to the console. Next, we use the setTimeout function to delay the execution of the code, and use the getLocalStorageData method in the code to obtain the data again. Since our delay time exceeds the expiration time of the data, the result obtained is null, indicating that the data has expired.

Through the above code examples, we can learn how to set and manage the expiration time of localstorage data. By adding timestamps or expiration timestamps, we can effectively control the timeliness of data and improve the reliability and performance of applications. Of course, in actual applications, we may also need to consider other factors, such as data update mechanisms and caching strategies, to better manage localstorage data.

The above is the detailed content of Manage and set the validity period of localstorage. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Learn about TRedis caching technology Learn about TRedis caching technology Jun 19, 2023 pm 08:01 PM

TRedis caching technology is a high-performance memory caching technology that can improve the performance and response speed of a website or application. In this article, we will introduce the basic concepts of TRedis caching technology and how to use it in your applications. What is TRedis caching technology? TRedis is a memory caching technology that stores frequently used data in memory, thereby increasing the speed of accessing this data. The main idea of ​​this technique is to reduce the load on the database or disk by using in-memory caching

Learn about ECache caching technology Learn about ECache caching technology Jun 20, 2023 am 08:10 AM

ECache is a Java caching framework that provides a simple yet powerful way to reduce the response time of computer applications. It enables applications to respond to client requests faster and improves system throughput by storing data in memory. In this article, we will introduce some basic knowledge of ECache caching technology, including its advantages, installation and usage, etc. 1. Advantages of ECache Improve system performance: ECache stores cache data in memory, which means that applications

How to set the expiration time of localstorage items How to set the expiration time of localstorage items Jan 11, 2024 am 09:06 AM

How to set the expiration time of localstorage requires specific code examples. With the rapid development of the Internet, front-end development often requires saving data in the browser. Localstorage is a commonly used WebAPI that aims to provide a way to store data locally in the browser. However, localstorage does not provide a direct way to set the expiration time. This article will introduce how to set the expiration time of localstorage through code examples.

Learn about Redisson caching technology Learn about Redisson caching technology Jun 21, 2023 am 09:54 AM

Redisson is a Redis-based caching solution for Java applications. It provides many useful features that make using Redis as a cache in Java applications more convenient and efficient. The caching functions provided by Redisson include: 1. Distributed mapping (Map): Redisson provides some APIs for creating distributed maps. These maps can contain key-value pairs, hash entries, or objects, and they can support sharing among multiple nodes.

At a glance: A quick overview of how to open JSP files At a glance: A quick overview of how to open JSP files Jan 31, 2024 pm 09:28 PM

JSP file opening method JSP (JavaServerPages) is a dynamic web page technology that allows programmers to embed Java code in HTML pages. JSP files are text files that contain HTML code, XML tags, and Java code. When a JSP file is requested, it is compiled into a JavaServlet and then executed by the web server. Methods of Opening JSP Files There are several ways to open JSP files. The easiest way is to use a text editor,

Differences between Go language and Golang: Do you know it? Differences between Go language and Golang: Do you know it? Feb 24, 2024 pm 06:06 PM

Go and Golang are the same programming language and there is no substantial difference between them. Go is the official name of the programming language, and Golang is the abbreviation commonly used by Go language developers in the Internet field. In this article, we will explore the characteristics, uses, and some specific code examples of the Go language to help readers better understand this powerful programming language. Go language is a statically compiled programming language developed by Google. It has the characteristics of efficiency, simplicity, and strong concurrency, and is designed to improve programmers' work efficiency.

How to extend the timeout of Ajax requests? How to extend the timeout of Ajax requests? Jan 26, 2024 am 10:09 AM

How to extend the expiration time of Ajax requests? When making network requests, we often encounter situations where we need to process large amounts of data or complex calculations, which may cause the request to time out and fail to return data normally. In order to solve this problem, we can ensure that the request can be completed successfully by extending the expiration time of the Ajax request. The following will introduce some methods and specific code examples to extend the expiration time of Ajax requests. When making an Ajax request using the timeout attribute, you can set the timeout attribute to

Localstorage analysis: What type of database technology is it? Localstorage analysis: What type of database technology is it? Jan 13, 2024 pm 01:29 PM

Understanding localstorage: What kind of database technology is it? In web development, data storage and processing have always been an important issue. With the continuous development of computer technology, various database technologies have also appeared one after another. Among them, localstorage is a widely used database technology. It is a local storage solution provided by HTML5 that can store and read data in the browser. This article will introduce the characteristics and usage of localstorage, and give specific codes.

See all articles