基于umi的开发模板

count_down.ts 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import { init_count_down, init_count_interval } from '@/utils/game_setting/game_config';
  2. const delay = (timeout: any) => new Promise(resolve => setTimeout(resolve, timeout));
  3. interface CountDownClockBase {
  4. task_id: NodeJS.Timeout;
  5. count: number;
  6. record_start_time: Date|any;
  7. record_stop_time: Date|any;
  8. is_clock_stop: boolean;
  9. is_restart_timeout: boolean;
  10. render: Function;
  11. }
  12. export class CountDownClock<CountDownClockBase> {
  13. static task_id: NodeJS.Timeout;
  14. static count = init_count_down;
  15. static record_start_time: Date|any;
  16. static record_stop_time: Date|any;
  17. static is_clock_stop: boolean = true;
  18. static is_restart_timeout: boolean = false;
  19. static render: Function = () => {};
  20. static _check_is_end() {
  21. if (this.count <= 0) {
  22. this.count = 0;
  23. this.render();
  24. clearInterval(this.task_id);
  25. return true;
  26. }
  27. return false;
  28. }
  29. static async start() {
  30. if (!this.is_clock_stop || this.is_restart_timeout) return;
  31. if (this.record_stop_time && this.record_start_time) {
  32. // 是暂停的开始, 精确计算暂停时间。
  33. const time_gap = (this.record_stop_time.getTime() - this.record_start_time.getTime()) % init_count_interval;
  34. this.is_restart_timeout = true;
  35. await delay(init_count_interval - time_gap);
  36. this.is_restart_timeout = false;
  37. if (this._check_is_end()) {
  38. return ;
  39. }
  40. this.count--;
  41. this.render();
  42. }
  43. this.is_clock_stop = false;
  44. clearInterval(this.task_id);
  45. this.task_id = setInterval(() => {
  46. if (this._check_is_end()) {
  47. return ;
  48. }
  49. this.count--;
  50. this.render();
  51. }, init_count_interval);
  52. this.record_start_time = new Date();
  53. }
  54. static async stop() {
  55. if (this.is_restart_timeout) { setTimeout(() => { this.stop() }, 1000); return; }
  56. this.is_clock_stop = true;
  57. clearInterval(this.task_id);
  58. this.record_stop_time = new Date();
  59. }
  60. static destory() {
  61. clearInterval(this.task_id);
  62. this.is_clock_stop = true;
  63. this.is_restart_timeout = false;
  64. this.record_start_time = undefined;
  65. this.record_stop_time = undefined;
  66. }
  67. }