-
Notifications
You must be signed in to change notification settings - Fork 1
/
fpsCtrl.js
46 lines (40 loc) · 1 KB
/
fpsCtrl.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
export function FpsCtrl(fps, callback) {
var delay = 1000 / fps,
time = null,
frame = -1,
tref
function loop(timestamp) {
if (time === null) time = timestamp
var seg = Math.floor((timestamp - time) / delay)
if (seg > frame) {
frame = seg
callback({
time: timestamp,
frame: frame
})
}
tref = requestAnimationFrame(loop)
}
this.isPlaying = false
this.frameRate = function(newfps) {
if (!arguments.length) return fps
fps = newfps
delay = 1000 / fps
frame = -1
time = null
}
this.start = function() {
if (!this.isPlaying) {
this.isPlaying = true
tref = requestAnimationFrame(loop)
}
}
this.pause = function() {
if (this.isPlaying) {
cancelAnimationFrame(tref)
this.isPlaying = false
time = null
frame = -1
}
}
}