乐闻世界logo
搜索文章和话题

Implementing a localStorage Storage Function with Expiry Time

浏览0
2024年8月5日 12:50

Implementing a localStorage storage function with expiry time capability requires defining a function that stores data along with its expiry timestamp in localStorage.

Here is a simple implementation example:

javascript
/** * Set localStorage with expiry time * @param {string} key - The key name for storage * @param {*} value - The value to store, which can be any serializable data * @param {number} ttl - Expiry time (in milliseconds) */ function setLocalStorageWithExpiry(key, value, ttl) { const now = new Date(); // Create an object containing the data and expiry timestamp const item = { value: value, expiry: now.getTime() + ttl, }; // Serialize the object and store it in localStorage localStorage.setItem(key, JSON.stringify(item)); } /** * Retrieve localStorage storage value * @param {string} key - The key name for storage * @returns {*} The stored value or null if the value is not found or expired */ function getLocalStorageWithExpiry(key) { const itemStr = localStorage.getItem(key); // If no matching storage item is found if (!itemStr) { return null; } const item = JSON.parse(itemStr); const now = new Date(); // Check if the expiry timestamp has been exceeded if (now.getTime() > item.expiry) { // If expired, remove the item from localStorage and return null localStorage.removeItem(key); return null; } // If not expired, return the stored value return item.value; } // Example usage // Store data named 'myData' with an expiry time of 1 hour (3600000 milliseconds) setLocalStorageWithExpiry('myData', { a: 1, b: 2 }, 3600000); // Retrieve the stored data const myData = getLocalStorageWithExpiry('myData'); console.log(myData); // If not expired, it will print the stored object { a: 1, b: 2 }

In this wrapper function, when storing data using the setLocalStorageWithExpiry function, an expiry timestamp is added to the object and the object is serialized before being stored in localStorage. When retrieving data using the getLocalStorageWithExpiry function, we first check if the current time has exceeded the expiry timestamp set during storage. If expired, the item is removed from localStorage and null is returned; if not expired, the stored value is returned.

标签:JavaScript前端