CoverageCheck / web /src /lib /replay.ts
TBM99's picture
Deploy coverage-check 3559250
23d418f verified
Raw History Blame Contribute Delete
922 Bytes
// Playing a recorded held-out run back at its real pace (each event's at_ms, written
// by coveragecheck.web.export from the run's own timings), optionally faster.
import type { RecordedEvent } from './types'
export type Replay = { cancel: () => void; finish: () => void }
/** Calls onEvent for each event at at_ms / speed. cancel() stops; finish() delivers the
* rest at once (the "skip to the answer" button). */
export function replay(events: RecordedEvent[], onEvent: (e: RecordedEvent) => void, speed = 1): Replay {
let next = 0
const timers: ReturnType<typeof setTimeout>[] = []
const deliver = (i: number) => {
while (next <= i) onEvent(events[next++])
}
events.forEach((e, i) => timers.push(setTimeout(() => deliver(i), e.at_ms / speed)))
const cancel = () => timers.forEach(clearTimeout)
return {
cancel,
finish: () => {
cancel()
deliver(events.length - 1)
},
}
}