forked from codedinc/eventloopclass
-
Notifications
You must be signed in to change notification settings - Fork 0
/
loop.js
73 lines (62 loc) · 1.51 KB
/
loop.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
var syscalls = require('syscalls');
var readables = {}; // {fd: callback}
var writables = {}; // {fd: callback}
exports.on = function(fd, event, callback) {
if (event == 'read') {
readables[fd] = callback;
} else {
writables[fd] = callback;
}
}
exports.remove = function(fd, event) {
if (event == 'read') {
delete readables[fd];
} else {
delete writables[fd];
}
};
var timers = [];
var timer = 0;
// loop.in(3, function () { ... })
exports.in = function(sec, callback) {
timers.push({ timeout: timer + sec, callback: callback });
};
var nextTicks = [];
exports.nextTick = function(callback) {
nextTicks.push(callback);
};
exports.run = function() {
// Here the event LOOP!
while (true) {
for (var i=0; i < nextTicks.length; i++) {
nextTicks[i]();
};
nextTicks = [];
var fds = syscalls.select(Object.keys(readables), Object.keys(writables), [], 1);
timer += 1;
for (var i=0; i < timers.length; i++) {
if (timers[i].timeout >= timer) {
timers[i].callback();
timers.splice(i, 1);
i--;
}
};
// fds = [
// [readables]
// [writables]
// [errors]
// ]
var readableFds = fds[0];
var writableFds = fds[1];
for (var i=0; i < readableFds.length; i++) {
var fd = readableFds[i];
var callback = readables[fd];
callback();
};
for (var i=0; i < writableFds.length; i++) {
var fd = writableFds[i];
var callback = writables[fd];
callback();
};
}
};