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
|
import { globals } from '../utils/window.js'
import Queue from './Queue.js'
const Animator = {
nextDraw: null,
frames: new Queue(),
timeouts: new Queue(),
immediates: new Queue(),
timer: () => globals.window.performance || globals.window.Date,
transforms: [],
frame (fn) {
// Store the node
var node = Animator.frames.push({ run: fn })
// Request an animation frame if we don't have one
if (Animator.nextDraw === null) {
Animator.nextDraw = globals.window.requestAnimationFrame(Animator._draw)
}
// Return the node so we can remove it easily
return node
},
timeout (fn, delay) {
delay = delay || 0
// Work out when the event should fire
var time = Animator.timer().now() + delay
// Add the timeout to the end of the queue
var node = Animator.timeouts.push({ run: fn, time: time })
// Request another animation frame if we need one
if (Animator.nextDraw === null) {
Animator.nextDraw = globals.window.requestAnimationFrame(Animator._draw)
}
return node
},
immediate (fn) {
// Add the immediate fn to the end of the queue
var node = Animator.immediates.push(fn)
// Request another animation frame if we need one
if (Animator.nextDraw === null) {
Animator.nextDraw = globals.window.requestAnimationFrame(Animator._draw)
}
return node
},
cancelFrame (node) {
node != null && Animator.frames.remove(node)
},
clearTimeout (node) {
node != null && Animator.timeouts.remove(node)
},
cancelImmediate (node) {
node != null && Animator.immediates.remove(node)
},
_draw (now) {
// Run all the timeouts we can run, if they are not ready yet, add them
// to the end of the queue immediately! (bad timeouts!!! [sarcasm])
var nextTimeout = null
var lastTimeout = Animator.timeouts.last()
while ((nextTimeout = Animator.timeouts.shift())) {
// Run the timeout if its time, or push it to the end
if (now >= nextTimeout.time) {
nextTimeout.run()
} else {
Animator.timeouts.push(nextTimeout)
}
// If we hit the last item, we should stop shifting out more items
if (nextTimeout === lastTimeout) break
}
// Run all of the animation frames
var nextFrame = null
var lastFrame = Animator.frames.last()
while ((nextFrame !== lastFrame) && (nextFrame = Animator.frames.shift())) {
nextFrame.run(now)
}
var nextImmediate = null
while ((nextImmediate = Animator.immediates.shift())) {
nextImmediate()
}
// If we have remaining timeouts or frames, draw until we don't anymore
Animator.nextDraw = Animator.timeouts.first() || Animator.frames.first()
? globals.window.requestAnimationFrame(Animator._draw)
: null
}
}
export default Animator
|