一般设置过期时间,是可以使用一个定时器不停的删除过期的数据。
但是这样就存在一个不准确的问题,因为定时器的时间不能设置的太短,否则就太消耗资源了。
但是如果在数据中加上过期时间,在数据被请求的时候跟当前的时间对比,如果数据过期,再返回数据过期(同时还可以删掉数据),而不是找不到数据才说数据过期,这样也是可以的。
同时可以再加上一个时间较长的定时器,用来处理已经过期而没有被请求到的数据,这样就完善了。
代码
// 一个临时数据存放方案
let
storeSymbol = Symbol(
'store'
);
class
Storage {
constructor
(createFunc = ()
=>
{ }, deleteFunc = ()
=>
{ }) {
this
[storeSymbol] = {};
this
.createFunc = createFunc;
this
.deleteFunc = deleteFunc;
this
.dataCleaner = setInterval(()
=>
{
for
(
let
key
of
this
[storeSymbol]) {
let
time = JSON.parse(
this
[storeSymbol][key]).time;
if
(time < Date.now()) {
this
[storeSymbol][key] =
null
;
}
}
},
1000
*
60
);
}
setItem(key, val, time) {
let
value = JSON.stringify({ val, time });
this
[storeSymbol][key] = value;
this
.createFunc(key, val, time);
}
getItem(key) {
let
value = JSON.parse(
this
[storeSymbol][key]);
if
(value.time < Date.now()) {
this
.deleteFunc(key);
delete
this
[storeSymbol][key];
return
null
;
}
return
value.val;
}
}
let
store =
new
Storage();
store.setItem(
'12'
,
'hhh'
, Date.now() +
1000
);
console.log(store.getItem(
'12'
));
// console.log(store);
setTimeout(()
=>
{
console.log(store.getItem(
'12'
));
// console.log(store);
},
1020
);