How to Set Expiry Time (TTL) for LocalStorage With Javascript

这篇博客介绍了如何使用JavaScript为浏览器的localStorage添加时间限制,使得存储的项在特定时间后自动失效。通过存储预期的过期时间和原始信息,当尝试获取项时检查当前时间是否超过存储的过期时间,从而实现懒惰式过期检查。示例代码展示了一个HTML页面,演示了如何设置和获取具有5秒过期时间的localStorage项。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This post will explain how to implement expiry times for items stored in the browsers localStorage.

If you’re familiar with the browsers localStorage object, you know that there’s no provision for providing an expiry time. However, we can use Javascript to add a TTL (Time to live) to invalidate items in localStorage after a certain period of time elapses.

If you just want to see a working example, you can skip to the last section

Here’s an overview of how we can achieve this:

  1. Store the expected time of expiry along with the original information to be stored
  2. When getting the item, compare the current time with the stored expiry time
  3. If the current time is greater than to stored expiry time, return null and remove the item from storage, otherwise, return the original information.

Let’s see how we can implement this using Javascript.

Storing Items with Expiry Time

Let’s create a function that allows you to set a key in localStorage, and store the expiry time along with it:

function setWithExpiry(key, value, ttl) {
	const now = new Date()

	// `item` is an object which contains the original value
	// as well as the time when it's supposed to expire
	const item = {
		value: value,
		expiry: now.getTime() + ttl,
	}
	localStorage.setItem(key, JSON.stringify(item))
}

Here, we create a new object with the original value as well as the expiry time, which is calculated by adding the TTL value in milliseconds to the current millisecond time.

We convert the item to a JSON string, since we can only store strings in localStorage.

Getting Items from Storage

We can verify the expiry time while retrieving items from the store:

function getWithExpiry(key) {
	const itemStr = localStorage.getItem(key)
	// if the item doesn't exist, return null
	if (!itemStr) {
		return null
	}
	const item = JSON.parse(itemStr)
	const now = new Date()
	// compare the expiry time of the item with the current time
	if (now.getTime() > item.expiry) {
		// If the item is expired, delete the item from storage
		// and return null
		localStorage.removeItem(key)
		return null
	}
	return item.value
}

Here we are expiring the item “lazily” - which is to say we check the expiry condition only when we want to retrieve it from storage. If the item has, in-fact expired, we remove the key from localStorage.

Full example

Let’s create a small HTML page which demonstrates how we can use localStorage with expiry:

  1. The “Set” button store the value in the input box to localStorage with a 5 second expiry
  2. The “Get” button fetches the value from localStorage and displays it below
  3. We make use of the setWithExpiry and getWithExpiry functions defined in the script
<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
		<title>LocalStorage Expiry Example</title>
	</head>

	<body>
		<button id="btn-set">Set</button>
		<input id="input-set" />
		<br /><br />
		<button id="btn-get">Get</button>
		<div>Value: <span id="value"></span></div>

		<script>
			const btnSet = document.getElementById("btn-set")
			const btnGet = document.getElementById("btn-get")
			const inputSet = document.getElementById("input-set")
			const valueDisplay = document.getElementById("value")

			btnSet.addEventListener("click", () => {
				setWithExpiry("myKey", inputSet.value, 5000)
			})

			btnGet.addEventListener("click", () => {
				const value = getWithExpiry("myKey")
				valueDisplay.innerHTML = value
			})

			function setWithExpiry(key, value, ttl) {
				const now = new Date()

				// `item` is an object which contains the original value
				// as well as the time when it's supposed to expire
				const item = {
					value: value,
					expiry: now.getTime() + ttl,
				}
				localStorage.setItem(key, JSON.stringify(item))
			}

			function getWithExpiry(key) {
				const itemStr = localStorage.getItem(key)

				// if the item doesn't exist, return null
				if (!itemStr) {
					return null
				}

				const item = JSON.parse(itemStr)
				const now = new Date()

				// compare the expiry time of the item with the current time
				if (now.getTime() > item.expiry) {
					// If the item is expired, delete the item from storage
					// and return null
					localStorage.removeItem(key)
					return null
				}
				return item.value
			}
		</script>
	</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值