Repository navigation
Expand file tree
/
Copy pathevent-loop-simulator.js
More file actions
86 lines (76 loc) · 2.04 KB
/
Copy pathevent-loop-simulator.js
File metadata and controls
86 lines (76 loc) · 2.04 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
/**
* Event Loop Mechanics & Concurrency Primitives
*/
export class EventLoopSimulator {
constructor() {
this.callStack = [];
this.microtaskQueue = [];
this.macrotaskQueue = [];
this.executionLog = [];
}
enqueueSync(taskName) {
this.callStack.push(taskName);
this.executionLog.push(`[Sync] ${taskName}`);
}
enqueueMicrotask(taskName) {
this.microtaskQueue.push(taskName);
}
enqueueMacrotask(taskName) {
this.macrotaskQueue.push(taskName);
}
/**
* Simulates a tick of the JavaScript Event Loop:
* 1. Synchronous call stack executes to completion.
* 2. All queued microtasks drain until the microtask queue is empty.
* 3. Next macrotask from macrotask queue executes.
*/
drainTick() {
// 1. Drain microtasks
while (this.microtaskQueue.length > 0) {
const task = this.microtaskQueue.shift();
this.executionLog.push(`[Microtask] ${task}`);
}
// 2. Execute one macrotask
if (this.macrotaskQueue.length > 0) {
const task = this.macrotaskQueue.shift();
this.executionLog.push(`[Macrotask] ${task}`);
// Any microtasks spawned during the macrotask drain immediately
while (this.microtaskQueue.length > 0) {
const micro = this.microtaskQueue.shift();
this.executionLog.push(`[Microtask] ${micro}`);
}
}
return [...this.executionLog];
}
}
/**
* Enterprise Debounce higher-order utility
*/
export function debounce(fn, waitMs) {
let timeoutId = null;
return function (...args) {
clearTimeout(timeoutId);
return new Promise((resolve) => {
timeoutId = setTimeout(() => {
resolve(fn.apply(this, args));
}, waitMs);
});
};
}
/**
* Enterprise Throttle higher-order utility
*/
export function throttle(fn, limitMs) {
let inThrottle = false;
return function (...args) {
if (!inThrottle) {
inThrottle = true;
const result = fn.apply(this, args);
setTimeout(() => {
inThrottle = false;
}, limitMs);
return result;
}
return undefined;
};
}