countdown.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // 工具类
  2. import util from './util.js';
  3. /**
  4. * 倒计时类
  5. */
  6. module.exports = {
  7. // 计时器句柄
  8. countIds: {},
  9. start(countId, app, dataIndex, endCallBack) {
  10. // console.log('start')
  11. this.onSetTimeList(countId, app, dataIndex, endCallBack, 0)
  12. },
  13. onSetTimeList(countId, app, dataIndex, endCallBack, deep = 0) {
  14. const _this = this;
  15. // 获取倒计时数据对象
  16. const countDownObj = app.data[dataIndex]
  17. // 获取当前时间,同时得到活动结束时间数组
  18. const newTime = new Date().getTime()
  19. // 对结束时间进行处理渲染到页面
  20. const endTime = new Date(util.format_date(countDownObj.date)).getTime();
  21. // 初始化倒计时数据
  22. countDownObj.dynamic = {
  23. // day: '00',
  24. hou: '00',
  25. min: '00',
  26. sec: '00'
  27. };
  28. // 如果活动未结束,对时间进行处理
  29. if (endTime - newTime > 0) {
  30. const diffTime = (endTime - newTime) / 1000;
  31. // 获取时、分、秒
  32. // day = parseInt(diffTime / 86400),
  33. const hou = parseInt(diffTime / 3600),
  34. min = parseInt(diffTime % 3600 / 60),
  35. sec = parseInt(diffTime % 3600 % 60);
  36. countDownObj.dynamic.hou = _this.timeFormat(hou)
  37. countDownObj.dynamic.min = _this.timeFormat(min)
  38. countDownObj.dynamic.sec = _this.timeFormat(sec)
  39. }
  40. // 渲染,然后每隔一秒执行一次倒计时函数
  41. app.setData({
  42. [`${dataIndex}`]: countDownObj
  43. })
  44. // 判断倒计时是否结束
  45. const isEnd = _this.isEnd(countDownObj);
  46. // 结束后执行回调函数
  47. isEnd && deep > 0 && endCallBack && endCallBack();
  48. // 重复执行
  49. _this.countIds[countId] && clearTimeout(_this.countIds[countId])
  50. if (!isEnd) {
  51. _this.countIds[countId] = setTimeout(() => {
  52. _this.onSetTimeList(countId, app, dataIndex, endCallBack, ++deep)
  53. }, 1000)
  54. }
  55. },
  56. /**
  57. * 判断倒计时是否结束
  58. * @param {*} countDownObj
  59. */
  60. isEnd(countDownObj) {
  61. const {
  62. dynamic
  63. } = countDownObj
  64. if (dynamic.hou == '00' && dynamic.min == '00' && dynamic.sec == '00') {
  65. return true
  66. }
  67. return false
  68. },
  69. /**
  70. * 小于10的格式化函数
  71. */
  72. timeFormat(param) {
  73. return param < 10 ? '0' + param : param;
  74. },
  75. };