123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778 |
- import { Component } from "cc";
- export class TimeManager {
- private _root: Component = null;
- private _callback_map = new Map<number, Function>();
- private _$timer_uuid = 0;
- private _server_time = 0;
- constructor(root: Component) {
- this._root = root;
- }
- set server_time(time: number) {
- this.server_time = time;
- }
- get server_time() {
- return this._server_time;
- }
- /**
- * 全局定时器
- * @param callback 回调
- * @param interval 以秒为单位的时间间隔
- * @param repeat 重复次数
- * @param delay 开始延时
- */
- public schedule(callback: Function, interval?: number, repeat?: number, delay?: number) {
- if (callback) {
- let uuid = ++this._$timer_uuid;
- this._callback_map.set(uuid, callback);
- this._root.schedule(callback, interval, repeat, delay);
- return uuid;
- }
- return -1;
- }
- /**
- * 释放定时器
- * @param uuid 任务标识
- */
- public unschedule(uuid: number) {
- if (uuid > 0) {
- let func = this._callback_map.get(uuid)
- if (func) {
- this._callback_map.delete(uuid);
- this._root.unschedule(func);
- }
- }
- }
- /**
- * 全局定时器
- * @param callback 回调
- * @param delay 开始延时
- */
- public scheduleOnce(callback: Function, delay: number = 0) {
- if (callback) {
- let uuid = ++this._$timer_uuid;
- this._callback_map.set(uuid, callback);
- this._root.scheduleOnce(() => {
- let func = this._callback_map.get(uuid);
- func && func();
- this.unschedule(uuid);
- }, Math.max(delay, 0));
- return uuid;
- }
- }
- clear() {
- this._$timer_uuid = 0;
- this._callback_map.forEach((func) => {
- this._root.unschedule(func);
- });
- this._callback_map.clear();
- }
- }
|