TimeMgr.ts 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import { _decorator, Component, director } from 'cc'
  2. const { ccclass, property } = _decorator
  3. const Max_Timer_Cnt: number = 10000
  4. /**
  5. * 时间管理
  6. */
  7. @ccclass('Manager/TimeMgr')
  8. export class TimeMgr extends Component {
  9. private static _inst: TimeMgr = null
  10. /**计时器字典 */
  11. private static _timerMap: Map<number, any> = new Map<number, any>()
  12. /**计时器下一个分配id */
  13. private static nextId: number = 0
  14. protected onLoad(): void {
  15. TimeMgr._inst = this
  16. director.addPersistRootNode(this.node)
  17. }
  18. public static async delay(time: number = 0): Promise<void> {
  19. return new Promise<void>((resolve, reject) => { this._inst.scheduleOnce(() => { resolve() }, time) })
  20. }
  21. /**
  22. * 设置一个计时器
  23. * @param callback 计时器回调 使用格式 function.bind(this)
  24. * @param interval 间隔时间
  25. * @param repeat 回调次数
  26. * @returns 返回计时器id
  27. */
  28. public static setTimer(callback: Function, interval: number, repeat: number = 1): number {
  29. let curCount = 0
  30. let id = this.nextId++
  31. if (id > Max_Timer_Cnt) id = 0
  32. const timerCallback = () => {
  33. callback && callback()
  34. ++curCount >= repeat && this.clearTimer(id)
  35. }
  36. this._timerMap.set(id, timerCallback)
  37. this._inst.schedule(timerCallback, interval, repeat)
  38. return id
  39. }
  40. /**
  41. * 清除一个计时器
  42. * @param timerId 计时器id
  43. */
  44. public static clearTimer(timerId: number): void {
  45. if (this._timerMap.has(timerId)) {
  46. this._inst.unschedule(this._timerMap.get(timerId))
  47. this._timerMap.delete(timerId)
  48. }
  49. }
  50. }