javascript - 如何在 00 :00 every day? 处重置 localStorage

标签 javascript local-storage

我的问题是我想每天在 00:00 重置 localStorage

即使不是 00:00,我也想在特定时间重置它。 是否可以通过setIntervallocalStorage.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/

相关文章:

javascript - 在 vm 脚本上下文中传递函数

javascript - 在完成 javascript css 后重复动画

javascript - 从本地存储中删除

javascript - Angular 2 LocalStorage key

javascript - 正则表达式验证应该允许特定值

javascript - D3js 如何在 .enter 上下文中追加 2 个相同级别的 child

javascript - 在 a.jpg 和 b.jpg 之间反复翻转图像

javascript - 无法正确获取localStorage中存储的数据

javascript - 在浏览器中存储 token

javascript - 我正在 localstorage 中存储一个值并尝试在 if 语句中使用它,但我只得到 null,我也对该值进行了字符串化