All files / integration sessionElapsed.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 0/0
100% Lines 14/14

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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                    37x 11x       115x 115x 115x       1x 1x 1x 1x       75x 75x       37x 37x     37x        
type SessionElapsedClockOptions = {
  now: () => number;
  setElapsed: (milliseconds: number) => void;
};
 
/** Drive elapsed-time presentation from either a live monotonic clock or replay time. */
export function createSessionElapsedClock(options: SessionElapsedClockOptions) {
  let startedAt: number | undefined;
  let ticker: ReturnType<typeof setInterval> | undefined;
 
  const refresh = (): void => {
    if (startedAt !== undefined) options.setElapsed(Math.max(0, options.now() - startedAt));
  };
 
  function stop(): void {
    if (ticker !== undefined) clearInterval(ticker);
    ticker = undefined;
    startedAt = undefined;
  }
 
  function start(): void {
    stop();
    startedAt = options.now();
    options.setElapsed(0);
    ticker = setInterval(refresh, 100);
  }
 
  function setReplayElapsed(milliseconds: number): void {
    stop();
    options.setElapsed(Math.max(0, milliseconds));
  }
 
  function reset(): void {
    stop();
    options.setElapsed(0);
  }
 
  return { start, stop, reset, refresh, setReplayElapsed };
}
 
export type SessionElapsedClock = ReturnType<typeof createSessionElapsedClock>;