我有一个简单的HTML5应用,我目前的工作,我想知道是否有可能在一段时间后除去在HTML5本地存储器中的项目,如:24小时后,取出此项目,等等一段时间后删除HTML5本地存储中的项目?
我在想JavaScript内置的Date对象可能就是我需要的东西。
这可能吗?一些代码示例会很好,如果可以的话,谢谢!
我有一个简单的HTML5应用,我目前的工作,我想知道是否有可能在一段时间后除去在HTML5本地存储器中的项目,如:24小时后,取出此项目,等等一段时间后删除HTML5本地存储中的项目?
我在想JavaScript内置的Date对象可能就是我需要的东西。
这可能吗?一些代码示例会很好,如果可以的话,谢谢!
如果你想这样做,我认为你基本上做手工,您可以存储日期与数据
//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);
}
一起。例如,您可以将时间戳存储在您存储的每个值旁边的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()存储/检索的对象的属性。但是,如果数组或对象非常大,或者你有很多,我可能会建议使用并行属性方法来提高效率。
window.setInterval(function() {
localStorage.setItem('nicwincount', 0);
},8640000); //24 * 60mins * 60sec
ps:nicwincount是您之前设置的本地存储。 localStorage.setItem('feeds',Ext.encode(feeds));
希望能帮助你。
这是否假设设备在页面上保持24小时?不可能! ;-) – markE 2016-06-18 17:08:12
使用此解决方案:
(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);
}
})();
谁需要留下?!如果您在过去的X时间访问该网站,并且如果它更大,则将其删除,这会检查您的localStorage。 – 2016-06-18 17:12:33
所以givme +1,如果它的工作对你的 – 2016-06-18 17:15:40
我想你的意思是1000 * 60 * 60 * 24 = 24小时未24天 – Yuhao 2018-01-15 19:15:19
我是这样解决的,但是我觉得应该为值[1]需要被解析成其前相比Date对象这个特殊的例子来说明。像这个新的日期(值[1]) – labago 2017-03-09 20:52:03