在设置值的时候将当前时间一并写入,读取值的时候先判断当前时间是否在允许的时间范围
设置时设置一个存入时间戳,取出的时候判断当前的时间戳与存入时间戳是否在有效期内,没在有效期内读取就会失败
class MyStorage {
get(key) {
const wrapValue = localStorage.getItem(key)
if (wrapValue == null) {
return undefined
}
const {value, expires} = JSON.parse(wrapValue)
if ((expires != null && Date.now() < expires) || expires == null) {
return value
}
return undefined
}
set(key, value, period) {
const wrapValue = { value };
if (period != null) {
wrapValue.expires = Date.now() + period;
}
localStorage.setItem(key, JSON.stringify(wrapValue));
}
}
function get(name) {
const record = JSON.parse(localStorage.getItem(name));
return record.time - Date.now() > 0 ? record: localStorage.removeItem('record');
}
function set(value) {
let record = {
time: Date.now() + 5000,
result: value
}
localStorage.setItem('record', JSON.stringify(record));
}
@liyan1105
class MyStorage {
get(key) {
const wrapValue = localStorage.getItem(key)
if (wrapValue == null) {
return undefined
}
const {value, expires} = JSON.parse(wrapValue)
- if ((expires != null && Date.now() < expires) || expires == null) {
+ if (!expires || Date.now() < expires) {
return value
}
-
+ localStorage.rmeoveItem(key)
return undefined
}
set(key, value, period) {
const wrapValue = { value };
if (period != null) {
wrapValue.expires = Date.now() + period;
}
localStorage.setItem(key, JSON.stringify(wrapValue));
}
}
1.存储时记录下有效截止时间
2.取数据时判断是否超过有效时间,在有效期内则返回,不在则提示或返回空并且将其删除
Most helpful comment