deno.land / x / xstate@xstate@4.33.6 / src / SimulatedClock.ts

SimulatedClock.ts
نووسراو ببینە
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
import { Clock } from './interpreter';
export interface SimulatedClock extends Clock { start(speed: number): void; increment(ms: number): void; set(ms: number): void;}
interface SimulatedTimeout { start: number; timeout: number; fn: (...args: any[]) => void;}export class SimulatedClock implements SimulatedClock { private timeouts: Map<number, SimulatedTimeout> = new Map(); private _now: number = 0; private _id: number = 0; public now() { return this._now; } private getId() { return this._id++; } public setTimeout(fn: (...args: any[]) => void, timeout: number) { const id = this.getId(); this.timeouts.set(id, { start: this.now(), timeout, fn }); return id; } public clearTimeout(id: number) { this.timeouts.delete(id); } public set(time: number) { if (this._now > time) { throw new Error('Unable to travel back in time'); }
this._now = time; this.flushTimeouts(); } private flushTimeouts() { [...this.timeouts] .sort(([_idA, timeoutA], [_idB, timeoutB]) => { const endA = timeoutA.start + timeoutA.timeout; const endB = timeoutB.start + timeoutB.timeout; return endB > endA ? -1 : 1; }) .forEach(([id, timeout]) => { if (this.now() - timeout.start >= timeout.timeout) { this.timeouts.delete(id); timeout.fn.call(null); } }); } public increment(ms: number): void { this._now += ms; this.flushTimeouts(); }}
xstate

Version Info

Tagged at
2 years ago