index.js 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. }
  61. else {
  62. this.macroTick();
  63. }
  64. },
  65. microTick: function () {
  66. var _this = this;
  67. this.tid = simpleTick(function () {
  68. _this.setRemain(_this.getRemain());
  69. if (_this.remain !== 0) {
  70. _this.microTick();
  71. }
  72. });
  73. },
  74. macroTick: function () {
  75. var _this = this;
  76. this.tid = simpleTick(function () {
  77. var remain = _this.getRemain();
  78. if (!utils_1.isSameSecond(remain, _this.remain) || remain === 0) {
  79. _this.setRemain(remain);
  80. }
  81. if (_this.remain !== 0) {
  82. _this.macroTick();
  83. }
  84. });
  85. },
  86. getRemain: function () {
  87. return Math.max(this.endTime - Date.now(), 0);
  88. },
  89. setRemain: function (remain) {
  90. this.remain = remain;
  91. var timeData = utils_1.parseTimeData(remain);
  92. if (this.data.useSlot) {
  93. this.$emit('change', timeData);
  94. }
  95. this.setData({
  96. formattedTime: utils_1.parseFormat(this.data.format, timeData),
  97. });
  98. if (remain === 0) {
  99. this.pause();
  100. this.$emit('finish');
  101. }
  102. },
  103. },
  104. });