一段时间后删除HTML5本地存储中的项目
Removing an item in HTML5 Local Storage after a period of time?
我有一个简单的HTML5应用程序,我目前正在开发中,我想知道是否有可能在一段时间后删除HTML5本地存储中的项目,例如:24小时后,删除此项目等。
我想JavaScript中内置的Date Object可能正是我所需要的。
这可能吗?如果可以的话,一些代码示例会很好,谢谢!
您可以将日期与数据一起存储
//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.stringfy/parse()输入时间戳作为存储/检索对象的属性。如果数组或对象非常大,或者您有很多,为了提高效率,我可能建议使用并行属性方法。
window.setInterval(function () {
localStorage.setItem('nicwincount', 0);
},8640000); //24 * 60mins * 60sec
ps:nicwincount是您之前设置的本地存储。localStorage.setItem("feeds",Ext.encode(feeds));
希望能帮助你。
相关文章:
- 通过另一个php应用程序将我的项目推送到Github存储库中
- JavaScript算法,提供每种可能的项目组合,并将它们存储在数组中
- 从本地存储中删除动态显示在
- 中的项目
- 使用 setTimeout() 函数从本地存储中删除项目
- 将数字存储在数组中会混淆如何根据值而不是索引来操作这些项目
- 我是否需要在设置项目之前从本地存储中删除项目
- Javascript 如何将项目推送到存储在对象中的数组中
- 使用 javascript 从本地存储获取项目
- 如何从传单上的本地存储和图层组中删除特定项目
- 如何在jqueryMoblie的本地存储中存储项目
- 在 Parse 中存储项目(Javascript)
- 如何移除 DOJO 数据存储添加到我提取的项目中的所有额外字段
- 循环(将项目存储在集合中)似乎迭代的次数比它应该的次数少
- 如何在浏览器窗口/选项卡关闭时删除本地存储项目
- 如何在用户重定向或注销该页面时删除引导会话存储项目
- 离子开关不会影响正确的本地存储项目
- 是否有< light >标记,我可以用它们来存储项目的服务器端Id
- Javascript或Jquery存储项目集合
- 在$listview中获取本地存储项目
- 打印本地存储项目的概览