-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-timers.js
More file actions
110 lines (86 loc) · 1.85 KB
/
2-timers.js
File metadata and controls
110 lines (86 loc) · 1.85 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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
'use strict';
class Reactor {
#tasks = [];
#active = false;
enqueue(fn) {
this.#tasks.push(fn);
}
start() {
this.#active = true;
while (this.#active && this.#tasks.length) {
const tasks = this.#tasks.splice(0);
for (const fn of tasks) fn();
}
}
stop() {
this.#tasks.splice(0);
this.#active = false;
}
get active() {
return this.#active;
}
}
const eventLoop = new Reactor();
// Timers
const timers = { id: 0 };
const timeouts = new Set();
const intervals = new Set();
const setTimeout = (fn, delay) => {
const id = ++timers.id;
const start = Date.now();
const check = () => {
if (!timeouts.has(id)) return;
if (Date.now() - start >= delay) {
timeouts.delete(id);
fn();
} else {
eventLoop.enqueue(check);
}
};
timeouts.add(id);
eventLoop.enqueue(check);
return id;
};
const clearTimeout = (id) => {
timeouts.delete(id);
};
const setInterval = (fn, interval) => {
const id = ++timers.id;
let start = Date.now();
const check = () => {
if (!intervals.has(id)) return;
if (Date.now() - start >= interval) {
start = Date.now();
fn();
}
eventLoop.enqueue(check);
};
intervals.add(id);
eventLoop.enqueue(check);
return id;
};
const clearInterval = (id) => {
intervals.delete(id);
};
// Usage
const timer = setTimeout(() => {
console.log('Should never execute');
}, 200);
clearTimeout(timer);
setTimeout(() => {
console.log('Executed after ~1000ms');
}, 1000);
setTimeout(() => {
console.log('Executed after ~3000ms');
console.log('Stopping loop');
eventLoop.stop();
}, 3000);
const intervalId = setInterval(() => {
console.log('Interval tick +500');
}, 500);
setTimeout(() => {
console.log('Executed after ~2000ms');
console.log('Clear interval');
clearInterval(intervalId);
}, 2000);
eventLoop.start();