parent
34b682bab5
commit
59cccd55a6
@ -0,0 +1,57 @@
|
||||
import { inactiveTimerErrorMessage, TIMER_STATUS_PENDING, TIMER_STATUS_RUNNING } from './consts.ts';
|
||||
import { TimrInactiveTimerError } from './errors.ts';
|
||||
import type { InternalTimerEntry } from './timer-entry.ts';
|
||||
import { assertTimerDelay } from './timer-validation.ts';
|
||||
import type { TimerClock, TimerHandle } from './types.ts';
|
||||
|
||||
export interface TimerHandleRuntime {
|
||||
readonly entries: Map<string, InternalTimerEntry>;
|
||||
readonly clock: TimerClock;
|
||||
cancelEntry(entry: InternalTimerEntry): void;
|
||||
armEntry(entry: InternalTimerEntry, delayMs: number): void;
|
||||
emitScheduled(entry: InternalTimerEntry): void;
|
||||
}
|
||||
|
||||
export function createTimerHandle(
|
||||
entry: InternalTimerEntry,
|
||||
runtime: TimerHandleRuntime
|
||||
): TimerHandle {
|
||||
const id = entry.id;
|
||||
const key = entry.key;
|
||||
return {
|
||||
get key() {
|
||||
return key;
|
||||
},
|
||||
get active() {
|
||||
const live = runtime.entries.get(key);
|
||||
return live !== undefined && live.id === id;
|
||||
},
|
||||
cancel() {
|
||||
const live = runtime.entries.get(key);
|
||||
if (live === undefined || live.id !== id) return false;
|
||||
runtime.cancelEntry(live);
|
||||
return true;
|
||||
},
|
||||
reschedule(delayMs: number) {
|
||||
const live = runtime.entries.get(key);
|
||||
if (live === undefined || live.id !== id) {
|
||||
throw new TimrInactiveTimerError(inactiveTimerErrorMessage(key), key);
|
||||
}
|
||||
if (live.status === TIMER_STATUS_RUNNING) {
|
||||
throw new TimrInactiveTimerError(inactiveTimerErrorMessage(key), key);
|
||||
}
|
||||
assertTimerDelay(delayMs);
|
||||
if (live.native !== null) {
|
||||
runtime.clock.clearTimeout(live.native);
|
||||
live.native = null;
|
||||
}
|
||||
const now = runtime.clock.now();
|
||||
live.scheduledAt = now;
|
||||
live.delayMs = delayMs;
|
||||
live.dueAt = now + delayMs;
|
||||
live.status = TIMER_STATUS_PENDING;
|
||||
runtime.armEntry(live, delayMs);
|
||||
runtime.emitScheduled(live);
|
||||
}
|
||||
};
|
||||
}
|
||||
Loading…
Reference in new issue