forked from wsick/Fayde
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathClockTimer.ts
55 lines (50 loc) · 1.75 KB
/
ClockTimer.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
module Fayde {
export interface ITimerListener {
OnTicked(lastTime: number, nowTime: number);
}
var requestAnimFrame = (function () {
return window.requestAnimationFrame ||
(<any>window).webkitRequestAnimationFrame ||
(<any>window).mozRequestAnimationFrame ||
(<any>window).oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function (callback) {
window.setTimeout(callback, 1000 / 200);
};
})();
export class ClockTimer {
private _Listeners: Fayde.ITimerListener[] = [];
private _LastTime: number = 0;
RegisterTimer(listener: Fayde.ITimerListener) {
var ls = this._Listeners;
var index = ls.indexOf(listener);
if (index > -1)
return;
ls.push(listener);
if (ls.length === 1)
this._RequestAnimationTick();
}
UnregisterTimer(listener: Fayde.ITimerListener) {
var ls = this._Listeners;
var index = ls.indexOf(listener);
if (index > -1)
ls.splice(index, 1);
}
private _DoTick() {
var nowTime = new Date().getTime();
var lastTime = this._LastTime;
this._LastTime = nowTime;
var ls = this._Listeners;
var len = ls.length;
if (len === 0)
return;
for (var i = 0; i < len; i++) {
ls[i].OnTicked(lastTime, nowTime);
}
this._RequestAnimationTick();
}
private _RequestAnimationTick() {
requestAnimFrame(() => this._DoTick());
}
}
}