123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123 |
- import { Component, director, macro } from "cc";
- export default class CountDownSchedule extends Component {
- private _lastUpdate = null;
- private _observers = null;
- public constructor() {
- super();
- this._observers = [];
- this._lastUpdate = (new Date()).getTime();
- };
- /**
- * 启动一个计时器
- * @param callback 每次回调
- * @param interval 执行间隔
- * @param key 计时器标识,用于移除使用
- * @example
- * <pre>
- * private const = 0
- * Global.cdSchedule.schedule(() => {
- * this.const++;
- * console.log(this.const);
- * if (this.const == 10) {
- * Global.cdSchedule.unschedule("test");
- * }
- * }, 1, "test");
- * </pre>
- */
- public schedule(callback, interval, key) {
- if (this._observers.length <= 0) {
- this._lastUpdate = (new Date()).getTime();
- director.getScheduler().schedule(this.onUpdateTime.bind(this), this, 0.05, macro.REPEAT_FOREVER, 0, false);
- }
- let obj = new CountDownObserver(callback, interval, key);
- this._observers.push(obj);
- }
- public onUpdateTime(dt: number) {
- let now = (new Date()).getTime();
- let deltaTime = (now - this._lastUpdate) / 1000;
- this._lastUpdate = now;
- for (let i = 0; i < this._observers.length; i++) {
- if (this._observers[i] && this._observers[i].update) {
- this._observers[i].update(deltaTime);
- }
- }
- return false;
- }
- /**
- * 通过计时器标识查找计时器是否存在
- * @param key 计时器标识
- * @returns
- */
- public isScheduled(key) {
- for (let i = 0; i < this._observers.length; i++) {
- if (this._observers[i]._key == key) {
- return true;
- }
- }
- return false;
- }
- /**
- * 移除计时器
- * @param key 计时器标识
- */
- public unschedule(key) {
- for (let i = 0; i < this._observers.length; i++) {
- if (this._observers[i]._key == key) {
- this._observers.splice(i, 1);
- break;
- }
- }
- }
- /**
- * 移除所以计时器
- */
- public unscheduleAll() {
- director.getScheduler().unscheduleAllForTarget(this);
- this._observers = [];
- }
- public changeScheduleKey(oldKey, newKey) {
- for (let i = 0; i < this._observers.length; i++) {
- if (this._observers[i]._key == oldKey) {
- this._observers[i]._key = newKey;
- break;
- }
- }
- }
- };
- class CountDownObserver {
- private _interval = 0;
- private _elapsed = 0;
- private _callback = null;
- private _key = null;
- public constructor(callback, interval, key) {
- this._callback = callback;
- this._interval = interval;
- this._key = key;
- }
- public update(dt) {
- this._elapsed += dt;
- if (this._elapsed > this._interval) {
- if (this._callback) {
- this._callback(this._elapsed);
- }
- this._elapsed = 0.0;
- }
- }
- }
|