Skip to content

Instantly share code, notes, and snippets.

@timn5835
Created January 11, 2021 16:36
Show Gist options
  • Save timn5835/1034394dbb69aa463c17968e5d04c236 to your computer and use it in GitHub Desktop.
Save timn5835/1034394dbb69aa463c17968e5d04c236 to your computer and use it in GitHub Desktop.
[Local Storage] Stores a value in browser local storage #js #localstorage #cookies
var alerted = getWithExpiry('covid19');
if (alerted != 'yes') {
$('.alert-dismissible.orange-bg.pr-0').addClass('d-flex');
}
$('body').on('close.bs.alert', '.alert-dismissible.orange-bg.pr-0', function () {
// localStorage.setItem('covid19','yes');
setWithExpiry('covid19', 'yes', 3600000)
});
function setWithExpiry(key, value, ttl) {
var now = new Date()
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
var item = {
value: value,
expiry: now.getTime() + ttl
}
localStorage.setItem(key, JSON.stringify(item))
}
function getWithExpiry(key) {
var itemStr = localStorage.getItem(key)
// if the item doesn't exist, return null
if (!itemStr) {
return null
}
var item = JSON.parse(itemStr)
var 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