我的问题是我想每天在 00:00
重置 localStorage
。
即使不是 00:00
,我也想在特定时间重置它。
是否可以通过setInterval
和localStorage.clear()
来解决?
欢迎任何建议。感谢您回答问题。
最佳答案
请注意,任何重置 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))
}
以及获取值函数:
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)
关于javascript - 如何在 00 :00 every day? 处重置 localStorage,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68600330/