-
Notifications
You must be signed in to change notification settings - Fork 0
/
timer.js
114 lines (94 loc) · 2.35 KB
/
timer.js
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
/*
create a timer with a function
prop_playing([val]) //gets/sets playing (boolean)
prop_tps([val]) //gets/sets ticks per second (float)
get_framerate()
*/
console.log("Loading timer.js...");
//performance.now shim
var now = (function() {
var performance = window.performance || {};
performance.now = (function() {
return performance.now ||
performance.webkitNow ||
performance.msNow ||
performance.oNow ||
performance.mozNow ||
function() { return new Date().getTime(); };
})();
return performance.now();
});
var Timer = function(in_action, in_tps) {
var tps; //ticks per second
var action; //function to call
var timeoutVar = null; //the return value from setTimeout
//Should be null if paused
var delay; //Delay in millis, derived from tps
if(typeof(in_action) != "function")
{ throw "didn't pass a function in Timer constructor" }
action = in_action;
setTPS(in_tps);
var fps = {};
fps.lastFPS = 0;
fps.lastSecondTime = 0;
fps.frameCount = 0;
fps.logFrame = function() {
var currTime = now();
if(currTime - fps.lastSecondTime > 1000) {
fps.lastFPS = fps.frameCount;
fps.frameCount = 0;
fps.lastSecondTime = currTime;
} else {
fps.frameCount++;
}
}
function setTPS(in_tps) {
//update values
tps = in_tps;
delay = 1000.0 / tps;
//if running, redo timeout delay
if(timeoutVar) {
clearTimeout(timeoutVar);
timeoutVar = setTimeout(tick, delay);
}
}
function tick() {
//do (and time) action
var startTime = now();
fps.logFrame();
action();
var duration = now() - startTime;
var newDelay = Math.max(delay - duration, 0);
//ready next action
timeoutVar = setTimeout(tick, newDelay);
}
//get/set tps
function tpsProp(newVal) {
if(newVal != undefined) {
if(newVal > 0)
{ setTPS(newVal) }
else
{ throw "Invalid TPS in tpsProp"; }
}
return tps;
}
//start playing, stop playing, or get current state
function playingProp(newVal) {
//set playing
if(newVal != undefined) {
if(newVal && !timeoutVar) { //start playing
tick();
} else if (!newVal && timeoutVar) { //stop playing
clearTimeout(timeoutVar);
timeoutVar = null;
}
}
return timeoutVar != null;
}
return {
playingProp: playingProp,
tpsProp: tpsProp,
getFPS: function() {return fps.lastFPS;},
}
}
console.log("Done");