当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 小程序中设置缓存过期的实现方法

小程序中设置缓存过期的实现方法

2020年03月09日  | 移动技术网IT编程  | 我要评论

需求是两张图片在这个时间段内交替显示,当天只弹一次图片。

后端返回的数据格式:

{
  "start": "2019/10/08 00:00:00",
  "end": "2019/10/30 23:59:59",
  "ads": [
    {
      "image": "xxxx",
      "uri": "wechat:zhizhuxy666"
    },
    {
      "image": "xxx",
      "uri": "wechat:zhizhuxy666"
    }
  ]
}

小程序中缓存没有过期时间,也就是说存储进去的缓存要自己手动清除,那么如何保证两张图片能够交替显示呢?

需求分析

  1. 一天只弹一次广告
  2. 图片轮流显示
  3. 只在时间范围内显示

这里有个关键是,如何知道时间有没有到第二天?

思路

需要用到两个缓存:

  1. showadvert:用于检测弹窗时间是否在有效期内
  2. showadvert${currentday}:用于检测当天是否弹过弹窗

为什么要用到两个?

因为这里有两个状态检测:一个是否在有效期内,一个是当天是否弹过弹窗。

如何判断时间有没有到第二天?

将所有天数的时间戳加上一天保存起来(ps:这个方法很蠢)。然后每次进入小程序都获取下当前的时间,对比下当天的时间是否大于保存的时间戳。如果超过就说明已经到了第二天。

为什么要加上一天?

因为后端返的开始时间是当天的凌晨,而真正要过完这一天是24点之后。一天的毫秒数:24 * 60 * 60 * 1000。

代码实现

变量的声明

声明需要使用的时间戳

const starttempstamp = new date(item.start).gettime()    
const endtempstamp = new date(item.end).gettime()
const onedaytempstamp = 24 * 60 * 60 * 1000   // 一天的时间戳
const now = (new date('2019/09/28 00:00:01')).gettime()

声明需要一共多少天,以及当天是第几天;这里使用math.ceil()向上取整

const allday = math.ceil((endtempstamp - starttempstamp) / onedaytempstamp)
const currentday = math.ceil((now - starttempstamp) / onedaytempstamp)

判断当前时间是否在时间有效期内内,如果在时间有效期内,就弹弹窗,如果不在就不弹

if (now > starttempstamp && now < endtempstamp) {
  ... //下面弹窗逻辑的实现
}else {
  this.setdata!({showadvert: false})
  wx.setstoragesync('showadvert', false) 
}

接下来开始写弹出弹窗的逻辑。

弹窗逻辑的实现

首先判断当天的时间戳是否大于前一天的时间戳,如果大于就说明到第二天了,如果小于说明今天还没有过去。

然后清除前一天的缓存

const table = []
for (let i = 1; i <= allday; i++) {
  table.push(starttempstamp + onedaytempstamp * i)
}
if (now > table[currentday - 2]) {
  wx.removestoragesync(`showadvert${table[currentday - 2]}`)
}

图片交替显示

let n = 0
if (currentday % item.ads.length === 0) {
  n = 1
} else if (currentday % item.ads.length === 1) {
  n = 0
}

检查当天广告是否弹出过

const advert = wx.getstoragesync(`showadvert${table[currentday - 1]}`) || false    
if (!advert) {
  this.setdata!({showadvert: true})
  wx.setstoragesync('showadvert', true)
}

弹出广告,并设置缓存

const timestamp = math.floor(new date().gettime() / 10000).tostring()
this.setdata!({
  advertlink: item.ads[n].image + `?timestamp=${timestamp}`,
  copywechat: item.ads[n].uri,
}, () => {
  wx.setstoragesync(`showadvert${table[currentday - 1]}`, true)
})

一进入页面读下本地缓存,是否要弹出弹窗。

onshow(){
  const showadvert = wx.getstoragesync('showadvert')
  this.setdata!({showadvert})
}

总结

这里最大的问题是如何判断当前的时间有没有过24点,自己一直没有想到比较好的解决方法,限于自己的水平,没有更好的方案,这里我只是记录下实现的过程,不喜勿喷,如果有更好的方案,欢迎指点。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网