-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
62 lines (51 loc) · 1.08 KB
/
index.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
const raf = require('raf');
class RafQueue {
constructor () {
this.id = undefined;
this.last = 0;
this.entries = [];
this.handles = {};
this.runner = this.run.bind(this);
}
/**
* @returns {number} Handle id.
*/
push (cb) {
if (this.last === Number.MAX_SAFE_INTEGER) {
this.last = 0;
}
var handle = this.last++;
this.entries.push(cb);
this.handles[handle] = cb;
this._raf();
return handle;
};
/**
* Run queued frames.
*/
run () {
this.id = undefined;
var entries = this.entries;
this.entries = [];
this.handles = {};
for (var i = 0; i < entries.length; i++) {
entries[i]();
}
}
_raf () {
if (this.id) return;
this.id = raf(this.runner);
};
/**
* @returns {boolean} If handle was found and cancelled.
*/
cancel (handle) {
var cb = this.handles[handle];
if (!cb) return false;
var index = this.entries.indexOf(cb);
if (index === -1) throw new Error();
this.entries.splice(index, 1);
return true;
};
}
module.exports = new RafQueue();