为方便调用对小程序缓存函数简单封装.同样适用h5 加缓存时间

小程序缓存不支持缓存时间因此简单封装了一下方便设置缓存时间

以下为了方便测试的h5版本.小程序只需要简单修改就可以了

<script>
var timestamp = parseInt(Date.parse(new Date())/1000);
cache('time',timestamp);
var time= cache('time');
console.log(time);

function cache(name,data,expires_in){
    if(!name)return;
    if(!expires_in)expires_in=60*60*24;//默认缓存时间1天    
    var timestamp = parseInt(Date.parse(new Date())/1000);
    if(!data){//获取缓存
        //var cache = wx.getStorageSync(name);//小程序
        var cache = localStorage.getItem(name);cache =JSON.parse(cache);//h5
        if(!cache)return '';var content='';
        if (cache.time >= timestamp && cache.content) {//判断缓存有效期
            content=cache.content;
        }return content;
    }else{//存储缓存        
        var cachetime= timestamp + expires_in;
        var cache={'time': cachetime, 'content': data};
        //wx.setStorageSync(name, cache);
        cache=JSON.stringify(cache);localStorage.setItem(name,cache);
        return true;
    }
}
</script>

小程序写法

cache:function(name,data,expires_in){
    if(!name)return;
    if(!expires_in)expires_in=60*60*24;//默认缓存时间1天    
    var timestamp = parseInt(Date.parse(new Date())/1000);
    if(!data){//获取缓存
        var cache = wx.getStorageSync(name);//小程序
        if(!cache)return '';var content='';
        if (cache.time >= timestamp && cache.content) {//判断缓存有效期
            content=cache.content;
        }return content;
    }else{//存储缓存        
        var cachetime= timestamp + expires_in;
        var cache={'time': cachetime, 'content': data};
        return wx.setStorageSync(name, cache);
    }
},

 

转载于:https://my.oschina.net/xiaogg/blog/3035595

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值