-
Notifications
You must be signed in to change notification settings - Fork 10
/
ticker.js
60 lines (49 loc) · 1.27 KB
/
ticker.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
let _requestAnimationFrame, _cancelAnimationFrame
if (typeof module !== 'undefined' &&
typeof exports !== 'undefined') {
/* for node.js */
_requestAnimationFrame = requestAnimationFrame || setImmediate
_cancelAnimationFrame = cancelAnimationFrame || clearImmediate
} else {
_requestAnimationFrame = requestAnimationFrame || setTimeout
_cancelAnimationFrame = cancelAnimationFrame || clearTimeout
}
function Ticker() {
this.list = []
this.last = null
this.started = false
this.id = null
this.loop = function() {
const
stamp = performance.now(),
last = this.last === null ? stamp : this.last,
dt = stamp - last
this.last = stamp
for (let i = 0; i < this.list.length; i++) this.list[i](dt)
this.id = _requestAnimationFrame(this.loop.bind(this))
}
this.add = function(fn) {
this.list.push(fn)
if (!this.started) {
this.started = true
this.loop()
}
}
this.remove = function(fn) {
for (let i = this.list.length - 1; i > -1; i--) {
if (this.list[i] === fn) {
this.list.splice(i, 1)
break
}
}
if (this.started && !this.list.length) {
this.started = false
_cancelAnimationFrame(this.id)
}
}
}
const ticker = new Ticker()
export {
Ticker,
ticker
}