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

相关文章

JVisualVM之Java性能监控与调优利器详解

《JVisualVM之Java性能监控与调优利器详解》本文将详细介绍JVisualVM的使用方法,并结合实际案例展示如何利用它进行性能调优,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全... 目录1. JVisualVM简介2. JVisualVM的安装与启动2.1 启动JVisualVM2

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

SpringBoot使用ffmpeg实现视频压缩

《SpringBoot使用ffmpeg实现视频压缩》FFmpeg是一个开源的跨平台多媒体处理工具集,用于录制,转换,编辑和流式传输音频和视频,本文将使用ffmpeg实现视频压缩功能,有需要的可以参考... 目录核心功能1.格式转换2.编解码3.音视频处理4.流媒体支持5.滤镜(Filter)安装配置linu

在Spring Boot中实现HTTPS加密通信及常见问题排查

《在SpringBoot中实现HTTPS加密通信及常见问题排查》HTTPS是HTTP的安全版本,通过SSL/TLS协议为通讯提供加密、身份验证和数据完整性保护,下面通过本文给大家介绍在SpringB... 目录一、HTTPS核心原理1.加密流程概述2.加密技术组合二、证书体系详解1、证书类型对比2. 证书获

Java使用MethodHandle来替代反射,提高性能问题

《Java使用MethodHandle来替代反射,提高性能问题》:本文主要介绍Java使用MethodHandle来替代反射,提高性能问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录一、认识MethodHandle1、简介2、使用方式3、与反射的区别二、示例1、基本使用2、(重要)

Java实现本地缓存的常用方案介绍

《Java实现本地缓存的常用方案介绍》本地缓存的代表技术主要有HashMap,GuavaCache,Caffeine和Encahche,这篇文章主要来和大家聊聊java利用这些技术分别实现本地缓存的方... 目录本地缓存实现方式HashMapConcurrentHashMapGuava CacheCaffe

SpringBoot整合Sa-Token实现RBAC权限模型的过程解析

《SpringBoot整合Sa-Token实现RBAC权限模型的过程解析》:本文主要介绍SpringBoot整合Sa-Token实现RBAC权限模型的过程解析,本文给大家介绍的非常详细,对大家的学... 目录前言一、基础概念1.1 RBAC模型核心概念1.2 Sa-Token核心功能1.3 环境准备二、表结

eclipse如何运行springboot项目

《eclipse如何运行springboot项目》:本文主要介绍eclipse如何运行springboot项目问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目js录当在eclipse启动spring boot项目时出现问题解决办法1.通过cmd命令行2.在ecl

Java中的Closeable接口及常见问题

《Java中的Closeable接口及常见问题》Closeable是Java中的一个标记接口,用于表示可以被关闭的对象,它定义了一个标准的方法来释放对象占用的系统资源,下面给大家介绍Java中的Clo... 目录1. Closeable接口概述2. 主要用途3. 实现类4. 使用方法5. 实现自定义Clos

Jvm sandbox mock机制的实践过程

《Jvmsandboxmock机制的实践过程》:本文主要介绍Jvmsandboxmock机制的实践过程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一、背景二、定义一个损坏的钟1、 Springboot工程中创建一个Clock类2、 添加一个Controller