Skip to content

Instantly share code, notes, and snippets.

@abbotto
Last active August 29, 2015 14:24
Show Gist options
  • Select an option

  • Save abbotto/4124039921e9f0c5d6a3 to your computer and use it in GitHub Desktop.

Select an option

Save abbotto/4124039921e9f0c5d6a3 to your computer and use it in GitHub Desktop.
localStorage with expiry date
// Save data with expiry date
var app = {
data: ''
};
// Enhanced localStorage with expiry
app.data = {
save: function(storageKey, value, expiry) {
if (!expiry) {
expiry = "360"; // Default expiry of 6 hours
}
var dueTime = expiry * 60 * 1E3;
var data = {
value: JSON.stringify(value),
timestamp: (new Date).getTime() + dueTime
};
window.localStorage.setItem(storageKey, JSON.stringify(data));
return value;
},
load: function(id) {
var item = JSON.parse(window.localStorage.getItem(id));
if (!item) {
return false;
}
return (new Date).getTime() < item.timestamp && JSON.parse(item.value);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment