通用化倒计时函数,支持传入配置对象、函数或者直接设置倒计时的秒数

免费公开代码,欢迎一起QQ交流

最近有个需求,一个商品列表,需要每件未付款的商品显示倒计时,倒计时过后对应商品自动删除,其他商品继续倒计时。然后网上找过,都不行,于是自己花了整整一个下午理清思路写了一个,然后现在封装起来了,现在使用起来贼方便。不多说了,下面看代码:

app.js

let countDowns = []//倒计时函数集合
globalData: {
  countDowns
}

util.js

let app = getApp()
/**倒计时模版-李青逸 2020/06/10 V2.2
 * 新增支持可以直接设置剩余秒数
 * 新增对传入日期格式的字符串和剩余秒数的逻辑判断
 * 修复设置结束后继续属性后,不足24小时时不显示天和时的BUG
 * @param {
    endTime, //结束时间或者直接设置剩余秒数
    showSecond, //是否显示秒数
    returnFormat, //返回日期格式
    continueAfterEnd, //结束时是否继续
    overTime //过期界限时间
  } setting 设置计时器属性或直接设置剩余秒数
* @param {function(参数) {//用参数来接收计时器返回的剩余时间}} fun1 存在剩余时间的函数
* @param {function() {//do something}} fun2 倒计时结束时的函数
* 中途取消倒计时必须使用util.clearUtilListInterval();否则会造成不必要的内存占用以及计时器重复
* //初始化计时器集合
let countDowns = []
//设置计时器属性
countDowns.push(util.timerTemplate({
  endTime: '2020/06/06 18:00:00',
  showSecond: true,//显示秒,默认为true
  returnFormat: 0,//返回格式 0: 1文字,默认为0
  continueAfterEnd: false,//结束时是否继续,返回过期时间,默认为false
  overTime: 86400//设置过期界限时间,单位秒,默认24小时
},function(time){
  console.log(`当前剩余:${time}`)
},function(){
  console.log('倒计时结束')
}));
//或者这样设置(传入秒数作为剩余时间,采用默认设置:显示秒;剩余时间返回格式为-- *天*:*:*;时间到立即终止倒计时;)
countDowns.push(util.timerTemplate(900,function(time){
  console.log(`当前剩余:${time}`)
},function(){
  console.log('倒计时结束')
}));
//运行计时器
app.globalData.countDowns = countDowns;
*/
function timerTemplate(setting,fun1,fun2){
  //若传入的setting是对象或者是日期格式的字符串则转换成时间戳,否则视为直接设置了剩余时间的秒数
  let endTime = setting.endTime ? (typeof setting.endTime == 'string' ? new Date(setting.endTime).getTime() / 1000 : setting.endTime) : (typeof setting == 'string' ? new Date(setting).getTime() / 1000 : setting),
      showSecond = setting.showSecond ? setting.showSecond : true,//显示秒
      returnFormat = setting.returnFormat ? setting.returnFormat : 0,//返回格式 0: 1文字
      continueAfterEnd = setting.continueAfterEnd ? setting.continueAfterEnd : false,//结束时是否继续,返回过期时间
      overTime = setting.overTime ? setting.overTime : 86400;//设置过期界限时间,单位秒,默认24小时
  let day,hour,minute,second;
  let com_day,com_hour,com_minute,com_second,timer;

  //若是对象或者是日期格式的字符串则根据现在时间计算剩余时间,否则视为直接设置了剩余时间的秒数
  let countDown = typeof setting.endTime == 'string' || typeof setting == 'string' ? endTime - new Date().getTime() / 1000 : endTime;
  timer = setInterval(function(){
    countDown -= 1;
    com_day = Math.abs(Math.floor((countDown / 86400)));
    com_hour = Math.abs(Math.floor(((countDown % 86400) / 3600)));
    com_minute = Math.abs(Math.floor((countDown / 60 % 60)));
    com_second = Math.abs(Math.floor((countDown % 60)));
    day = com_day > 0 ? com_day : '';
    hour = com_hour > 0 ? (com_hour < 10 ? '0' + com_hour : com_hour) : '';
    minute = com_minute < 10 ? '0' + com_minute : com_minute;
    second = com_second < 10 ? '0' + com_second : com_second;
    if(second == 60){//秒钟为60时归0
      second = '00';
      minute = com_minute < 10 ? '0' + (com_minute + 1) : com_minute + 1;
    }
    if(minute == 60){//分钟为60时归0
      minute = '00';
      minute = countDown > 3600 ? (com_hour < 10 ? '0' + (com_hour + 1) : com_hour + 1) : '';
    }
    if (continueAfterEnd) {//设置了结束时继续计时,返回过期时间
      if (countDown >= 0 || Math.abs(countDown) < overTime) {
        // console.log(countDown,day,hour,minute,second)
        fun1(`${day ? (countDown < 0 ? '-' : '') + day + '天' : ''}${hour ? (countDown < 0 ? '-' : '') + hour + (returnFormat == 0 ? ':' : '时') : ''}${(countDown < 0 ? '-' : '') + minute}${returnFormat == 0 ? ':' : '分'}${countDown < 0 && showSecond ? '-' : ''}${showSecond ? second : ''}${returnFormat == 0 && showSecond ? '' : '秒'}`);
      } else {//规定的时间已到期,需要做什么
        clearInterval(timer)
        fun2();
      }
    }else{
      if (countDown > 0) {
        fun1(`${day ? day+'天' : ''}${hour ? returnFormat == 0 ? hour + ':' : hour + '时' : ''}${minute}${returnFormat == 0 ? ':' : '分'}${showSecond ? second : ''}${returnFormat == 0 && showSecond ? '' : '秒'}`);
      } else {
        clearInterval(timer)
        fun2();
      }
    }
  },1000);
  //抛出计时器对象,以便外部清空此计时器
  return timer;
}

function clearUtilListInterval(){
  for (const time in app.globalData.countDowns) {
    clearInterval(app.globalData.countDowns[time])
  }
  app.globalData.countDowns = []
}

module.exports = {
  timerTemplate,
  clearUtilListInterval
}

页面js 例如index.js

let util = require('../../../../utils/util.js')
let app = getApp()
let that

onLoad: function () {
  that = this
},
onShow: function () {
  this.getOrderList();
  this.getRefundList();
},
onHide: function(){
  //页面隐藏时清空当前页全部倒计时以释放内存占用
  util.clearUtilListInterval();
},
onUnload: function(){
  util.clearUtilListInterval();
},
// 给所有未付款的商品加上倒计时
setCountDownToAllOrder: function(){
  let countDowns = []//倒计时函数集合
  //读取全部订单列表orderList中是否含有endTime字段
  this.data.orderList.forEach((item,index) => {
    if (item.endTime) {
      // 将符合条件的订单设置计时器
      countDowns.push(util.timerTemplate(item.endTime,function(time){
        //orderList[index].time
        that.setData({
          [`orderList[${index}].time`]: time
        })
      },function(){
        // 倒计时结束后删除对应商品和倒计时
        let orderList = that.data.orderList;
        orderList.splice(index,1);
        that.setData({orderList});
        util.clearUtilListInterval();
        that.setCountDownToAllOrder();
        wx.showModal({
          title: '提示',
          content: `您购买的商品【${item.title}】已超过约定支付时间,已自动取消该订单`,
          showCancel: false
        })
      }));
    }
  });
  app.globalData.countDowns = countDowns;
},
getOrderList: function(){
  wx.request({
    url: '***/testData.json',
    header: {
      'Content-Type': 'application/json'
    },
    success: res => {
      let data = res.data
      that.setData({
        orderList: data.testData_ActiveOrderIndex_orderList
      })
      that.setCountDownToAllOrder();
    },
    fail: res => {
      wx.showToast({
        title: '网络错误(获取订单列表)',
        icon: "none",
        mask: true
      })
    }
  })
}

效果图
img
img
img

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

猿某人_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值