1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
-
- import { init_count_down, init_count_interval } from '@/utils/game_setting/game_config';
-
- const delay = (timeout: any) => new Promise(resolve => setTimeout(resolve, timeout));
-
- interface CountDownClockBase {
- task_id: NodeJS.Timeout;
- count: number;
- record_start_time: Date|any;
- record_stop_time: Date|any;
- is_clock_stop: boolean;
- is_restart_timeout: boolean;
- render: Function;
- }
-
- export class CountDownClock<CountDownClockBase> {
- static task_id: NodeJS.Timeout;
- static count = init_count_down;
- static record_start_time: Date|any;
- static record_stop_time: Date|any;
- static is_clock_stop: boolean = true;
- static is_restart_timeout: boolean = false;
- static render: Function = () => {};
-
- static _check_is_end() {
- if (this.count <= 0) {
- this.count = 0;
- this.render();
- clearInterval(this.task_id);
- return true;
- }
- return false;
- }
-
- static async start() {
- if (!this.is_clock_stop || this.is_restart_timeout) return;
- if (this.record_stop_time && this.record_start_time) {
- // 是暂停的开始, 精确计算暂停时间。
- const time_gap = (this.record_stop_time.getTime() - this.record_start_time.getTime()) % init_count_interval;
- this.is_restart_timeout = true;
- await delay(init_count_interval - time_gap);
- this.is_restart_timeout = false;
- if (this._check_is_end()) {
- return ;
- }
- this.count--;
- this.render();
- }
- this.is_clock_stop = false;
- clearInterval(this.task_id);
- this.task_id = setInterval(() => {
- if (this._check_is_end()) {
- return ;
- }
- this.count--;
- this.render();
- }, init_count_interval);
- this.record_start_time = new Date();
- }
- static async stop() {
- if (this.is_restart_timeout) { setTimeout(() => { this.stop() }, 1000); return; }
- this.is_clock_stop = true;
- clearInterval(this.task_id);
- this.record_stop_time = new Date();
- }
- static destory() {
- clearInterval(this.task_id);
- this.is_clock_stop = true;
- this.is_restart_timeout = false;
- this.record_start_time = undefined;
- this.record_stop_time = undefined;
- }
- }
|