-
Notifications
You must be signed in to change notification settings - Fork 9
/
yielder.js
43 lines (39 loc) · 1.1 KB
/
yielder.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
function time() {
return new Date().valueOf();
}
function Yielder() {
this.startTime = time();
this.shouldYield = function(continueFunction){
if (time() <= this.startTime + 100)
return false;
info("yielding to UI thread");
this.startTime = time();
this.nextAction = setTimeout(continueFunction, 0);
return true;
};
this.cancel = function(){
if (this.nextAction)
clearTimeout(this.nextAction);
};
}
function politeEach(array, f, onComplete, yielder) {
yielder = yielder || new Yielder();
var index = 0;
function iterate() {
while(index < array.length) {
f(index, array[index]);
index++;
if (yielder.shouldYield(iterate))
return;
}
if (onComplete) onComplete();
}
iterate();
}
function politeMap(array, f, onComplete, yielder) {
yielder = yielder || new Yielder();
var result = [];
politeEach(array, function(index, value) {
result[index] = f(index,value);
}, function() {onComplete(result);}, yielder);
}