This repository has been archived by the owner on May 25, 2021. It is now read-only.
forked from anthonyshort/raf-queue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
95 lines (80 loc) · 1.52 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
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
var raf = require('raf');
var queue = [];
var requestId;
var id = 0;
/**
* Add a job to the queue passing in
* an optional context to call the function in
*
* @param {Function} fn
* @param {Object} cxt
*/
function frame (fn, cxt) {
var frameId = id++;
var length = queue.push({
id: frameId,
fn: fn,
cxt: cxt
});
if(!requestId) requestId = raf(flush);
return frameId;
};
/**
* Remove a job from the queue using the
* frameId returned when it was added
*
* @param {Number} id
*/
frame.cancel = function (id) {
for (var i = queue.length - 1; i >= 0; i--) {
if(queue[i].id === id) {
queue.splice(i, 1);
break;
}
}
};
/**
* Add a function to the queue, but only once
*
* @param {Function} fn
* @param {Object} cxt
*/
frame.once = function (fn, cxt) {
for (var i = queue.length - 1; i >= 0; i--) {
if(queue[i].fn === fn) return;
}
frame(fn, cxt);
};
/**
* Get the current queue length
*/
frame.queued = function () {
return queue.length;
};
/**
* Clear the queue and remove all pending jobs
*/
frame.clear = function () {
queue = [];
if(requestId) raf.cancel(requestId);
requestId = null;
};
/**
* Fire a function after all of the jobs in the
* current queue have fired. This is usually used
* in testing.
*/
frame.defer = function (fn) {
raf(raf.bind(null, fn));
};
/**
* Flushes the queue and runs each job
*/
function flush () {
while(queue.length) {
var job = queue.shift();
job.fn.call(job.cxt);
}
requestId = null;
}
module.exports = frame;