Skip to content

Instantly share code, notes, and snippets.

@Buildstarted
Created November 14, 2013 05:47
Show Gist options
  • Save Buildstarted/7462047 to your computer and use it in GitHub Desktop.
Save Buildstarted/7462047 to your computer and use it in GitHub Desktop.
4 different timer implementations in typescript
module Utilities {
export class Timer implements eg.IUpdateable {
private OnTick: eg.EventHandler;
private _start: number;
private _interval: number;
private _started: boolean;
private _lastTime: number;
constructor(interval: eg.TimeSpan);
constructor(interval: eg.TimeSpan, callback?: Function);
constructor(start: eg.TimeSpan, interval?: eg.TimeSpan);
constructor(start: eg.TimeSpan, interval?: any, callback?: Function) {
this.OnTick = new eg.EventHandler();
this._start = start.Milliseconds;
if (interval instanceof eg.TimeSpan) {
this._interval = interval.Milliseconds;
} else if (interval instanceof Function) {
callback = <Function>interval;
} else {
this._interval = start.Milliseconds;
}
if (callback) {
this.OnTick.Bind(callback);
}
this._lastTime = new eg.GameTime().Total.Milliseconds;
}
public Start(): void {
this._started = true;
}
private Tick(): void {
this.OnTick.Trigger();
this._lastTime += this._interval;
}
public Stop(): void {
this._started = false;
}
public Update(gameTime: eg.GameTime): void {
if (this._started && this._lastTime < gameTime.Total.Milliseconds) {
this.Tick();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment