Last active
August 29, 2015 14:24
-
-
Save abbotto/4124039921e9f0c5d6a3 to your computer and use it in GitHub Desktop.
localStorage with expiry date
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // 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