Skip to content

Instantly share code, notes, and snippets.

@itsHall
Last active October 14, 2021 20:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itsHall/3a8f5b13add4525d5eee0236bcf6138f to your computer and use it in GitHub Desktop.
Save itsHall/3a8f5b13add4525d5eee0236bcf6138f to your computer and use it in GitHub Desktop.
Functions to handle localstorage object with expiration
function setWithExpiry(key, value, ttl) {
const now = new Date()
const item = {
value: value,
expiry: now.getTime() + ttl
}
localStorage.setItem(key, JSON.stringify(item))
}
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment