index.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var component_1 = require('../common/component');
  4. var utils_1 = require('./utils');
  5. function simpleTick(fn) {
  6. return setTimeout(fn, 30);
  7. }
  8. component_1.VantComponent({
  9. props: {
  10. useSlot: Boolean,
  11. millisecond: Boolean,
  12. time: {
  13. type: Number,
  14. observer: 'reset',
  15. },
  16. format: {
  17. type: String,
  18. value: 'HH:mm:ss',
  19. },
  20. autoStart: {
  21. type: Boolean,
  22. value: true,
  23. },
  24. },
  25. data: {
  26. timeData: utils_1.parseTimeData(0),
  27. formattedTime: '0',
  28. },
  29. destroyed: function () {
  30. clearTimeout(this.tid);
  31. this.tid = null;
  32. },
  33. methods: {
  34. // 开始
  35. start: function () {
  36. if (this.counting) {
  37. return;
  38. }
  39. this.counting = true;
  40. this.endTime = Date.now() + this.remain;
  41. this.tick();
  42. },
  43. // 暂停
  44. pause: function () {
  45. this.counting = false;
  46. clearTimeout(this.tid);
  47. },
  48. // 重置
  49. reset: function () {
  50. this.pause();
  51. this.remain = this.data.time;
  52. this.setRemain(this.remain);
  53. if (this.data.autoStart) {
  54. this.start();
  55. }
  56. },
  57. tick: function () {
  58. if (this.data.millisecond) {
  59. this.microTick();
  60. } else {
  61. this.macroTick();
  62. }
  63. },
  64. microTick: function () {
  65. var _this = this;
  66. this.tid = simpleTick(function () {
  67. _this.setRemain(_this.getRemain());
  68. if (_this.remain !== 0) {
  69. _this.microTick();
  70. }
  71. });
  72. },
  73. macroTick: function () {
  74. var _this = this;
  75. this.tid = simpleTick(function () {
  76. var remain = _this.getRemain();
  77. if (!utils_1.isSameSecond(remain, _this.remain) || remain === 0) {
  78. _this.setRemain(remain);
  79. }
  80. if (_this.remain !== 0) {
  81. _this.macroTick();
  82. }
  83. });
  84. },
  85. getRemain: function () {
  86. return Math.max(this.endTime - Date.now(), 0);
  87. },
  88. setRemain: function (remain) {
  89. this.remain = remain;
  90. var timeData = utils_1.parseTimeData(remain);
  91. if (this.data.useSlot) {
  92. this.$emit('change', timeData);
  93. }
  94. this.setData({
  95. formattedTime: utils_1.parseFormat(this.data.format, timeData),
  96. });
  97. if (remain === 0) {
  98. this.pause();
  99. this.$emit('finish');
  100. }
  101. },
  102. },
  103. });