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 hour
If you want to do this I think you basically have to do it manually. For example, you could store the timestamp in a localStorage slot alongside each value you're storing, and then check the timestamp against the current time at some regular interval like page load or setTimeout or something.
Example:
//this function sets the value, and marks the timestamp
function setNewVal(prop)
{
window.localStorage[prop] = Math.random();
window.localStorage[prop+"timestamp"] = new Date();
}
//this function checks to see which ones need refreshing
function someRucurringFunction()
{
//check each property in localStorage
for (var prop in window.localStorage)
{ //if the property name contains the string "timestamp"
if (prop.indexOf("timestamp") != -1)
{ //get date objects
var timestamp = new Date(window.localStorage[prop]);
var currentTime = new Date();
//currently set to 30 days, 12 hours, 1 min, 1s (don't set to 0!)
var maxAge = (1000 * 1) *//s
(60 * 1) *//m
(60 * 12) *//h
(24 * 30); //d
if ((currentTime - timestamp) > maxAge)
{//if the property is too old (yes, this really does work!)
//get the string of the real property (this prop - "timestamp")
var propString = prop.replace("timestamp","");
//send it to some function that sets a new value
setNewVal(propString);
}
}
}
}
//set the loop
window.setInterval(someRucurringFunction,(1000*60*60);
EDIT: mrtsherman's method would totally work as well. Similarly, you could enter the timestamp as a property of an object you might be storing/retrieving with JSON.stringify/parse(). If either the array or the object are very large, or you have very many of them, I'd probably suggest using the parallel property method for efficiency, though.