19 lines
859 B
TypeScript
19 lines
859 B
TypeScript
import type { Clock } from '../src/server/clock.js';
|
|
export class ManualClock implements Clock {
|
|
time = Date.now(); id = 0;
|
|
timers = new Map<number, { at: number; callback: () => void }>();
|
|
now = () => this.time;
|
|
setTimeout = (callback: () => void, delay: number) => { const id = ++this.id; this.timers.set(id, { at: this.time + delay, callback }); return id; };
|
|
clearTimeout = (id: any) => { this.timers.delete(id); };
|
|
async advance(ms: number) {
|
|
const target = this.time + ms;
|
|
for (;;) {
|
|
const next = [...this.timers.entries()].filter(([, t]) => t.at <= target).sort((a, b) => a[1].at - b[1].at)[0];
|
|
if (!next) break;
|
|
this.time = next[1].at; this.timers.delete(next[0]); next[1].callback();
|
|
await new Promise(r => setTimeout(r, 20));
|
|
}
|
|
this.time = target; await new Promise(r => setTimeout(r, 20));
|
|
}
|
|
}
|