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

编程入门 行业动态 更新时间:2024-10-28 14:35:25

How to Set Expiry <a href=https://www.elefans.com/category/jswz/34/1771096.html style=Time (TTL) for LocalStorage With Javascript"/>

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

本文发布于:2024-02-05 08:02:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1673661.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Time   Expiry   Set   Javascript   LocalStorage

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!