forked from podgorniy/javascript-toolbox
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathworker.js
More file actions
57 lines (45 loc) · 1.16 KB
/
worker.js
File metadata and controls
57 lines (45 loc) · 1.16 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
48
49
50
51
52
53
54
55
56
57
var worker = (function () {
var stack;
var callsGap;
var sinseLastCall;
var lastCall;
// functions stack
stack = [];
// time between calls
callsGap = 999;
// last time when function from stack was processed
lastCall = 0;
// async iterator on functions stack
function processStack () {
var thisMoment;
var funcArgsPair;
thisMoment = now();
sinseLastCall = thisMoment - lastCall;
// there are items to process and this function wasn't called
// recentrly (less, than callsGap time)
if (sinseLastCall >= callsGap && stack.length) {
// remember call time
lastCall = thisMoment;
// process first item
funcArgsPair = stack.shift()();
funcArgsPair.func.apply(window, funcArgsPair.args);
// plan next process tick
// we plan it anyway, in case, new function will
// be added less, than in callsGap time
setTimeout(processStack, callsGap);
}
}
function now () {
return new Date().getTime();
}
function isIsArrayLike (obj) {
return length in obj && typeof obj !== 'function';
}
return function (func, args) {
stack.push({
func : func,
args : isIsArrayLike(args) ? args : [args]
});
processStack();
};
}());