Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing an item in HTML5 Local Storage after a period of time?

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!

like image 380
Dropped43 Avatar asked Feb 05 '12 06:02

Dropped43


People also ask

How do I delete data from local storage after some time?

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.

Which one is used for removing the item from local storage?

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.

How long do items stay in local storage?

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.

Can we set timer for local storage?

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.


2 Answers

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);
}
like image 185
mrtsherman Avatar answered Sep 19 '22 12:09

mrtsherman


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);
  }

})();
like image 26
Guy Ytzhak Avatar answered Sep 20 '22 12:09

Guy Ytzhak