DEV Community

Saba beigi
Saba beigi

Posted on • Edited on

6 2

Set Expiry Time (TTL) for LocalStorage With Javascript

1.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))
}```




2.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
}`

---


Enter fullscreen mode Exit fullscreen mode

AWS GenAI LIVE image

How is generative AI increasing efficiency?

Join AWS GenAI LIVE! to find out how gen AI is reshaping productivity, streamlining processes, and driving innovation.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay