-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
47 lines (41 loc) · 1.04 KB
/
Copy pathindex.js
File metadata and controls
47 lines (41 loc) · 1.04 KB
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
'use strict';
module.exports = function debounce (ms) {
var timeout = null
var queue = []
var ended = false
var readPending = false
var candidate = null
function callback(end, data) {
if (queue.length) queue.shift()(end, data)
}
return function(read) {
var timeoutWon = false
return function next (end, cb) {
if (cb) queue.push(cb)
if (ended) return callback(ended);
if (readPending) return;
if (end) return read(end, callback);
ended = ended || end;
readPending = true
read(end, function (end, data) {
readPending = false
if (end) {
// always emit last item
ended = end;
return callback(null, candidate)
}
candidate = data
if (timeoutWon) {
timeoutWon = false
if (!queue.length) return
}
clearTimeout(timeout);
timeout = setTimeout(function() {
timeoutWon = true
callback(null, candidate);
}, ms)
return next(end)
})
}
}
}