File size: 922 Bytes
23d418f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
// 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)
    },
  }
}