【发布时间】:2012-02-27 04:09:41
【问题描述】:
我目前正在开发一个简单的 HTML5 应用程序,我想知道是否可以在一段时间后删除 HTML5 本地存储中的项目,例如:24 小时后,删除该项目等。
我认为 JavaScript 中内置的 Date 对象可能是我需要的。
这可能吗?如果可以的话,一些代码示例会很好,谢谢!
【问题讨论】:
标签: javascript html local-storage
我目前正在开发一个简单的 HTML5 应用程序,我想知道是否可以在一段时间后删除 HTML5 本地存储中的项目,例如:24 小时后,删除该项目等。
我认为 JavaScript 中内置的 Date 对象可能是我需要的。
这可能吗?如果可以的话,一些代码示例会很好,谢谢!
【问题讨论】:
标签: javascript html local-storage
您可以将日期与数据一起存储
//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);
}
【讨论】:
使用此解决方案:
(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);
}
})();
【讨论】:
如果您想这样做,我认为您基本上必须手动进行。例如,您可以将时间戳存储在您存储的每个值旁边的 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() 存储/检索的对象的属性。如果数组或对象非常大,或者你有很多,我可能会建议使用并行属性方法来提高效率。
【讨论】:
(new Date).getTime()
window.setInterval(function () {
localStorage.setItem('nicwincount', 0);
},8640000); //24 * 60mins * 60sec
ps:nicwincount 是你之前设置的localstorage。 localStorage.setItem('feeds', Ext.encode(feeds));
希望能帮到你。
【讨论】: