index.js 2.5 KB

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