TimeManager.ts 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import { Component } from "cc";
  2. export class TimeManager {
  3. private _root: Component = null;
  4. private _callback_map = new Map<number, Function>();
  5. private _$timer_uuid = 0;
  6. private _server_time = 0;
  7. constructor(root: Component) {
  8. this._root = root;
  9. }
  10. set server_time(time: number) {
  11. this.server_time = time;
  12. }
  13. get server_time() {
  14. return this._server_time;
  15. }
  16. /**
  17. * 全局定时器
  18. * @param callback 回调
  19. * @param interval 以秒为单位的时间间隔
  20. * @param repeat 重复次数
  21. * @param delay 开始延时
  22. */
  23. public schedule(callback: Function, interval?: number, repeat?: number, delay?: number) {
  24. if (callback) {
  25. let uuid = ++this._$timer_uuid;
  26. this._callback_map.set(uuid, callback);
  27. this._root.schedule(callback, interval, repeat, delay);
  28. return uuid;
  29. }
  30. return -1;
  31. }
  32. /**
  33. * 释放定时器
  34. * @param uuid 任务标识
  35. */
  36. public unschedule(uuid: number) {
  37. if (uuid > 0) {
  38. let func = this._callback_map.get(uuid)
  39. if (func) {
  40. this._callback_map.delete(uuid);
  41. this._root.unschedule(func);
  42. }
  43. }
  44. }
  45. /**
  46. * 全局定时器
  47. * @param callback 回调
  48. * @param delay 开始延时
  49. */
  50. public scheduleOnce(callback: Function, delay: number = 0) {
  51. if (callback) {
  52. let uuid = ++this._$timer_uuid;
  53. this._callback_map.set(uuid, callback);
  54. this._root.scheduleOnce(() => {
  55. let func = this._callback_map.get(uuid);
  56. func && func();
  57. this.unschedule(uuid);
  58. }, Math.max(delay, 0));
  59. return uuid;
  60. }
  61. }
  62. clear() {
  63. this._$timer_uuid = 0;
  64. this._callback_map.forEach((func) => {
  65. this._root.unschedule(func);
  66. });
  67. this._callback_map.clear();
  68. }
  69. }