uniapp设置缓存过期时间

在uniapp中设置缓存过期时间通常涉及到本地存储的操作。你可以使用uni.setStorageSync或uni.setStorage来设置缓存项,并结合JavaScript的Date对象来计算过期时间。

以下是一个示例代码,展示如何设置缓存并在一定时间后过期:

// 设置缓存
function setCache(key, value, expireSeconds) {
  const currentTime = Date.now();
  const expireTime = currentTime + expireSeconds * 1000; // 转换为毫秒
  uni.setStorage({
    key: key,
    data: {
      value: value,
      expireTime: expireTime
    },
    success: function() {
      console.log('缓存设置成功');
    }
  });
}

// 获取缓存
function getCache(key) {
  const res = uni.getStorageSync(key);
  if (res && res.expireTime > Date.now()) {
    return res.value;
  } else {
    uni.removeStorage({
      key: key,
      success: function() {
        console.log('缓存已过期,已移除');
      }
    });
    return null; // 缓存过期,返回null
  }
}

// 使用示例
const key = 'myCacheKey';
const value = 'myCacheValue';
const expireSeconds = 30; // 缓存30秒
setCache(key, value, expireSeconds);

// 稍后获取缓存
const cachedValue = getCache(key);
console.log(cachedValue); // 缓存过期时会打印null

在这个示例中,setCache函数接受一个键、值和过期时间(秒),然后将值与过期时间存储在一起。getCache函数用于检查缓存是否过期,如果没有过期则返回值,如果过期则移除缓存并返回null。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值