57 lines
1.4 KiB
TypeScript
57 lines
1.4 KiB
TypeScript
import { singleton } from '../decorators/singleton'
|
|
import Clock from './ClockTimer'
|
|
import { Delayed } from './Delayed'
|
|
|
|
/**
|
|
* 全局定时器
|
|
*/
|
|
@singleton
|
|
export class Schedule {
|
|
clock: Clock = new Clock()
|
|
gameClock: Map<string, Delayed> = new Map()
|
|
|
|
public start() {
|
|
this.clock.start()
|
|
}
|
|
|
|
beginSchedule(millisecond: number, handler: Function, name: string): void {
|
|
if (this.gameClock.has(name) && this.gameClock.get(name)?.active) {
|
|
console.log(`当前已存在进行中的clock: ${ name }`)
|
|
this.gameClock.get(name).clear()
|
|
this.gameClock.delete(name)
|
|
}
|
|
let timeOverFun = function () {
|
|
handler && handler()
|
|
}
|
|
this.gameClock.set(name, this.clock.setTimeout(timeOverFun, millisecond, name))
|
|
}
|
|
|
|
/**
|
|
* 取消某个计时器
|
|
*/
|
|
stopSchedule(name: string): number {
|
|
console.log(`manual stop schedule: ${ name }`)
|
|
if (!this.gameClock.has(name)) {
|
|
return -1
|
|
}
|
|
let clock = this.gameClock.get(name)
|
|
if (!clock.active) {
|
|
this.gameClock.delete(name)
|
|
return -1
|
|
}
|
|
let time = clock.elapsedTime
|
|
clock.clear()
|
|
this.gameClock.delete(name)
|
|
return time
|
|
}
|
|
|
|
/**
|
|
* 判断某个定时器是否active
|
|
* @param {string} name
|
|
* @return {boolean}
|
|
*/
|
|
scheduleActive(name: string): boolean {
|
|
return this.gameClock.has(name) && this.gameClock.get(name).active
|
|
}
|
|
}
|