我有一个简单的HTML5应用程序,我目前正在处理,我想知道是否可以在一段时间后删除HTML5本地存储中的项目,例如:24小时后,删除此项目等。< / p>
我认为JavaScript内置的Date Object可能就是我需要的东西。
这可能吗?如果可以的话,一些代码示例会很好,谢谢!
答案 0 :(得分:13)
您可以将日期与数据一起存储
//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);
}
答案 1 :(得分:1)
如果你想这样做,我认为你基本上必须手动完成。例如,您可以将时间戳存储在localStorage插槽旁边,并存储每个值,然后按照页面加载或setTimeout等某些常规间隔检查时间戳与当前时间。
示例:
//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);
编辑:mrtsherman的方法也可以完成。同样,您可以输入时间戳作为可能使用JSON.stringify / parse()存储/检索的对象的属性。如果数组或对象非常大,或者你有很多,我可能建议使用parallel属性方法来提高效率。
答案 2 :(得分:1)
使用此解决方案:
(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);
}
})();
答案 3 :(得分:-3)
window.setInterval(function () {
localStorage.setItem('nicwincount', 0);
},8640000); //24 * 60mins * 60sec
ps:nicwincount是您之前设置的本地存储。 localStorage.setItem('feeds',Ext.encode(feeds));
希望可以帮到你。