I have a simple HTML5 App that I am currently working on and I'm wondering if it's possible to remove a item in HTML5 Local Storage after a period of time, like: after 24 hours, remove this item, etc.
I'm thinking that Date Object built into JavaScript would probably be what I need.
Is this possible? Some code examples would be nice if you could, thanks!
The only thing you can do is set the delete statement in a timeout of 1 hour. This requires the user to stay on your page or the timeout won't be executed. You can also set an expiration field. When the user revisits your site, check the expiration and delete the storage on next visit as the first thing you do.
The removeItem() method removes the specified Storage Object item. The removeItem() method belongs to the Storage Object, which can be either a localStorage object or a sessionStorrage object.
localStorage is similar to sessionStorage , except that while localStorage data has no expiration time, sessionStorage data gets cleared when the page session ends — that is, when the page is closed.
You can set Local storage like this: 1- On windows load check if you have already local storage for variables min and sec , if yes get both values using localStorage. getItem("item") else set both variables to start values.
You could store the date along with the data
//add data we are interested in tracking to an array
var values = new Array();
var oneday = new Date();
oneday.setHours(oneday.getHours() + 24); //one day from now
values.push("hello world");
values.push(oneday);
try {
localStorage.setItem(0, values.join(";"));
}
catch (e) { }
//check if past expiration date
var values = localStorage.getItem(0).split(";");
if (values[1] < new Date()) {
localStorage.removeItem(0);
}
Use This Solution:
(function () {
var lastclear = localStorage.getItem('lastclear'),
time_now = (new Date()).getTime();
// .getTime() returns milliseconds so 1000 * 60 * 60 * 24 = 24 days
if ((time_now - lastclear) > 1000 * 60 * 60 * 24) {
localStorage.clear();
localStorage.setItem('lastclear', time_now);
}
})();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With