js localStorage设置过期时间

这篇博客介绍了如何利用JavaScript的localStorage来创建一个简单的数据缓存系统。`cacheSet`和`cacheGet`两个函数分别用于设置和获取缓存数据,并处理了缓存过期和强制过期的情况。此方法适用于前端开发中的数据存储和本地持久化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// 存数据
cacheSet('key', '123', 1000); // 1000秒后过期

// 取数据
cacheGet('key')


/**
 * 设置 localStoryage
 * @param key 键
 * @param value 值
 * @param expire 过期时间(秒) 缓存最大时间请勿超过 forceTime 否则每次都会清空数据 (未设置请忽略)
 * @return bool true
 */
function cacheSet(key, value = '', expire = 0){
    // 当前时间戳
    var nowTime = Math.ceil(Date.now()/1000);
    // 设置数据
    localStorage.setItem(key, JSON.stringify(value))
    // 判断是否有过期时间
    if (expire > 0)
    {
        // 设置过期时间
        localStorage.setItem(key + '_expire', (nowTime + parseInt(expire)))
    }
    else
    {
        // 设置过期时间
        localStorage.setItem(key + '_expire', 0)
    }
    return true;
}

/**
 * 读取 localStoryage
 * @param key
 * @return bool|originData false|originData
 */
function cacheGet(key)
{
    // 当前时间戳
    var nowTime = Math.ceil(Date.now()/1000);
    // 获取键时间戳
    var rawCacheDataExpire = localStorage.getItem(key + '_expire');
    var cacheDataExpire = parseInt(rawCacheDataExpire);

    // 强制过期时间 为0时忽略 用于解决缓存时间与本地时间差距过大(例本地更改了计算机时间)
    var forceTime = 3600;
    // 判断用户是否删除了过期时间 判断是否设置了过期时间 判断是否超过过期时间 判断当前计算机时间与设置的过期时间差距是否过大
    if ((rawCacheDataExpire === null) || (cacheDataExpire > 0) && ((nowTime > cacheDataExpire) || (forceTime > 0 && Math.abs(cacheDataExpire - nowTime) > forceTime)))
    {
        // 删除过期key
        localStorage.removeItem(key)
        // 删除过期时间
        localStorage.removeItem(key + '_expire')
        return false;
    }

    // 获取数据
    cacheData = JSON.parse(localStorage.getItem(key));

    if (cacheData === null || cacheData === false)
    {
        return false;
    }
    // 返回数据
    return cacheData;
}

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值