-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
33 lines (30 loc) · 956 Bytes
/
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
module.exports = function (fn, hashingfn, wait, options) {
var timeouts = {};
var maxTimeouts = {};
options = options || {};
if (typeof options === "boolean") {
options = {immediate: options};
}
return function () {
var context = this;
var args = arguments;
var hash = hashingfn.apply(this, arguments);
var timeout = timeouts[hash];
var maxTimeout = options.maxWait && maxTimeouts[hash];
var callNow = options.immediate && !timeout;
function later() {
delete timeouts[hash];
if (maxTimeouts[hash]) {
clearTimeout(maxTimeouts[hash]);
delete maxTimeouts[hash];
}
if (!options.immediate) fn.apply(context, args);
}
if (timeout) clearTimeout(timeout);
timeouts[hash] = setTimeout(later, wait);
if (options.maxWait && !maxTimeout) {
maxTimeouts[hash] = setTimeout(later, options.maxWait);
}
if (callNow) return fn.apply(context, args);
};
};