提问人:Jay0813 提问时间:7/31/2021 最后编辑:Penny LiuJay0813 更新时间:3/8/2023 访问量:618
如何每天在 00:00 重置 localStorage?
How can I reset localStorage at 00:00 every day?
问:
我的问题是我想每天重置。localStorage
00:00
即使不是,我也想在特定时间重置它。
有没有可能通过和解决它?00:00
setInterval
localStorage.clear()
欢迎任何建议。感谢您回答问题。
答:
3赞
Alireza Ahmadi
7/31/2021
#1
请注意,任何要重置的代码都不能保证重置值,因为用户当时可能没有打开页面。
因此,您可以为数据添加自定义过期时间,如下所示:localStorage
localStorage
function setWithExpiry(key, value, ttl) {
const now = new Date()
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
const item = {
value: value,
expiry: now.getTime() + ttl,
}
localStorage.setItem(key, JSON.stringify(item))
}
和 get value 函数:
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
// if the item doesn't exist, return null
if (!itemStr) {
return null
}
const item = JSON.parse(itemStr)
const now = new Date()
// compare the expiry time of the item with the current time
if (now.getTime() > item.expiry) {
// If the item is expired, delete the item from storage
// and return null
localStorage.removeItem(key)
return null
}
return item.value
}
和用法:(以毫秒为单位的值)TTL
setWithExpiry("myKey", some value, 5000)
评论