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

2023-11-29 10:40

本文主要是介绍How to Set Expiry Time (TTL) for LocalStorage With Javascript,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

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 expireconst 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 nullif (!itemStr) {return null}const item = JSON.parse(itemStr)const now = new Date()// compare the expiry time of the item with the current timeif (now.getTime() > item.expiry) {// If the item is expired, delete the item from storage// and return nulllocalStorage.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 expireconst 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 nullif (!itemStr) {return null}const item = JSON.parse(itemStr)const now = new Date()// compare the expiry time of the item with the current timeif (now.getTime() > item.expiry) {// If the item is expired, delete the item from storage// and return nulllocalStorage.removeItem(key)return null}return item.value}</script></body>
</html>

这篇关于How to Set Expiry Time (TTL) for LocalStorage With Javascript的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/432518

相关文章

Spring IOC的三种实现方式详解

《SpringIOC的三种实现方式详解》:本文主要介绍SpringIOC的三种实现方式,在Spring框架中,IOC通过依赖注入来实现,而依赖注入主要有三种实现方式,构造器注入、Setter注入... 目录1. 构造器注入(Cons编程tructor Injection)2. Setter注入(Setter

Java function函数式接口的使用方法与实例

《Javafunction函数式接口的使用方法与实例》:本文主要介绍Javafunction函数式接口的使用方法与实例,函数式接口如一支未完成的诗篇,用Lambda表达式作韵脚,将代码的机械美感... 目录引言-当代码遇见诗性一、函数式接口的生物学解构1.1 函数式接口的基因密码1.2 六大核心接口的形态学

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC

Spring Boot统一异常拦截实践指南(最新推荐)

《SpringBoot统一异常拦截实践指南(最新推荐)》本文介绍了SpringBoot中统一异常处理的重要性及实现方案,包括使用`@ControllerAdvice`和`@ExceptionHand... 目录Spring Boot统一异常拦截实践指南一、为什么需要统一异常处理二、核心实现方案1. 基础组件

java中的HashSet与 == 和 equals的区别示例解析

《java中的HashSet与==和equals的区别示例解析》HashSet是Java中基于哈希表实现的集合类,特点包括:元素唯一、无序和可包含null,本文给大家介绍java中的HashSe... 目录什么是HashSetHashSet 的主要特点是HashSet 的常用方法hasSet存储为啥是无序的

IDEA运行spring项目时,控制台未出现的解决方案

《IDEA运行spring项目时,控制台未出现的解决方案》文章总结了在使用IDEA运行代码时,控制台未出现的问题和解决方案,问题可能是由于点击图标或重启IDEA后控制台仍未显示,解决方案提供了解决方法... 目录问题分析解决方案总结问题js使用IDEA,点击运行按钮,运行结束,但控制台未出现http://

解决Spring运行时报错:Consider defining a bean of type ‘xxx.xxx.xxx.Xxx‘ in your configuration

《解决Spring运行时报错:Considerdefiningabeanoftype‘xxx.xxx.xxx.Xxx‘inyourconfiguration》该文章主要讲述了在使用S... 目录问题分析解决方案总结问题Description:Parameter 0 of constructor in x

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

JSON字符串转成java的Map对象详细步骤

《JSON字符串转成java的Map对象详细步骤》:本文主要介绍如何将JSON字符串转换为Java对象的步骤,包括定义Element类、使用Jackson库解析JSON和添加依赖,文中通过代码介绍... 目录步骤 1: 定义 Element 类步骤 2: 使用 Jackson 库解析 jsON步骤 3: 添

Java中注解与元数据示例详解

《Java中注解与元数据示例详解》Java注解和元数据是编程中重要的概念,用于描述程序元素的属性和用途,:本文主要介绍Java中注解与元数据的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参... 目录一、引言二、元数据的概念2.1 定义2.2 作用三、Java 注解的基础3.1 注解的定义3.2 内