Countdown.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. Component({
  2. properties: {
  3. endTime: {
  4. type: String,
  5. value: ''
  6. },
  7. startTime:{
  8. type: String,
  9. value: ''
  10. }
  11. },
  12. data: {
  13. countdown: {
  14. days: "00",
  15. hours: "00",
  16. minutes: "00",
  17. seconds: "00"
  18. },
  19. isStart:false,
  20. showCountdown: true,
  21. timer: null
  22. },
  23. lifetimes: {
  24. attached() {
  25. if (this.properties.endTime) {
  26. const target = new Date(this.properties.endTime.replace(/-/g, '/')).getTime();
  27. const start = this.properties.startTime?new Date(this.properties.startTime.replace(/-/g, '/')).getTime():0;
  28. this.startCountdown(target,start);
  29. }
  30. },
  31. detached() {
  32. this.clearTimer();
  33. }
  34. },
  35. methods: {
  36. startCountdown(endTime,startTime) {
  37. this.clearTimer();
  38. this.data.timer = setInterval(() => {
  39. const now = Date.now();
  40. let diff = Math.floor((endTime - now) / 1000);
  41. if(startTime > now){
  42. diff = Math.floor((endTime - startTime) / 1000);
  43. }
  44. if (diff <= 0) {
  45. this.clearTimer();
  46. this.setData({ showCountdown: false,isStart:false });
  47. this.triggerEvent("finish"); // 通知父组件倒计时结束
  48. return;
  49. }
  50. if(startTime > 0 && startTime > now && this.data.isStart){
  51. return;
  52. }
  53. const days = Math.floor(diff / (60 * 60 * 24));
  54. const hours = Math.floor((diff % (60 * 60 * 24)) / 3600);
  55. const minutes = Math.floor((diff % 3600) / 60);
  56. const seconds = diff % 60;
  57. this.setData({
  58. isStart:true,
  59. countdown: {
  60. days: this.formatNum(days),
  61. hours: this.formatNum(hours),
  62. minutes: this.formatNum(minutes),
  63. seconds: this.formatNum(seconds)
  64. }
  65. });
  66. }, 1000);
  67. },
  68. formatNum(n) {
  69. return n < 10 ? "0" + n : n;
  70. },
  71. clearTimer() {
  72. if (this.data.timer) {
  73. clearInterval(this.data.timer);
  74. this.data.timer = null;
  75. }
  76. }
  77. }
  78. });