Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

封装一个localstorage的setItem和getItem方法 #128

Open
Sunny-117 opened this issue Nov 3, 2022 · 2 comments
Open

封装一个localstorage的setItem和getItem方法 #128

Sunny-117 opened this issue Nov 3, 2022 · 2 comments

Comments

@Sunny-117
Copy link
Owner

No description provided.

@2239351258
Copy link

实现可过期的localstorage数据

可以在存储数据时,在数据中加入一个过期时间戳,然后在获取数据时,先判断该数据的时间戳是否已经过期,如果已过期,则将该数据从 localStorage 中删除,并返回 null,否则返回该数据。

function setWithExpiration(key, value, expirationMinutes) {
  const expirationMS = expirationMinutes * 60 * 1000;
  const record = { value: value, timestamp: new Date().getTime() + expirationMS };
  localStorage.setItem(key, JSON.stringify(record));
}

function getWithExpiration(key) {
  const record = JSON.parse(localStorage.getItem(key));
  if (!record) {
    return null;
  }
  if (new Date().getTime() > record.timestamp) {
    localStorage.removeItem(key);
    return null;
  }
  return record.value;
}
// 使用方法
setWithExpiration("data", { foo: "bar" }, 1); // 设置 data 数据,1 分钟后过期
const data = getWithExpiration("data"); // 获取 data 数据
console.log(data); // { foo: "bar" }
setTimeout(() => {
  const expiredData = getWithExpiration("data"); // 获取 data 数据
  console.log(expiredData); // null,数据已过期,被自动删除
}, 60 * 1000); // 1 分钟后

@cscty
Copy link

cscty commented Jul 5, 2023

function setWithExpiration(key, value, expirationMinutes) {
const expirationsMS = expirationMinutes * 60 * 1000
const record = {
value: value,
timestamp: new Date().getTime() + expirationsMS,
}
localStorage.setItem(key, JSON.stringify(record))
}
function getWithExpiration(key) {
const record = JSON.parse(localStorage.getItem(key))
if (!record) {
return null
}
if (new Date().getTime() >= record.timestamp) {
localStorage.removeItem('key')
return null
} else {
return record
}
}
setWithExpiration('a', '123', 1 / 20)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants