All files / player-terminal/src/node render-throttle.ts

91.42% Statements 32/35
84.21% Branches 16/19
100% Functions 6/6
91.42% Lines 32/35

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 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69                      4x 4x 4x 4x     4x 5x 4x   1x 1x     4x 7x 7x     7x 7x 1x 1x   6x 6x     4x   8x     8x 8x 4x 4x 4x   4x 1x   3x     1x 1x           4x     4x    
export interface RenderThrottle {
  request: () => void;
  dispose: () => void;
}
 
export interface CreateRenderThrottleOptions {
  minIntervalMs?: number;
  now?: () => number;
}
 
export function createRenderThrottle(render: () => void, options: CreateRenderThrottleOptions = {}): RenderThrottle {
  const minIntervalMs = normalizeMinInterval(options.minIntervalMs);
  const now = options.now ?? Date.now;
  let disposed = false;
  let lastRenderAtMs = Number.NEGATIVE_INFINITY;
  let timer: NodeJS.Timeout | undefined;
 
  const clearTimer = (): void => {
    if (!timer) {
      return;
    }
    clearTimeout(timer);
    timer = undefined;
  };
 
  const run = (): void => {
    timer = undefined;
    Iif (disposed) {
      return;
    }
    const remainingMs = minIntervalMs - (now() - lastRenderAtMs);
    if (remainingMs > 0) {
      timer = setTimeout(run, remainingMs);
      return;
    }
    lastRenderAtMs = now();
    render();
  };
 
  return {
    request: () => {
      Iif (disposed) {
        return;
      }
      const remainingMs = minIntervalMs - (now() - lastRenderAtMs);
      if (remainingMs <= 0) {
        clearTimer();
        run();
        return;
      }
      if (timer) {
        return;
      }
      timer = setTimeout(run, remainingMs);
    },
    dispose: () => {
      disposed = true;
      clearTimer();
    },
  };
}
 
function normalizeMinInterval(value: number | undefined): number {
  Iif (typeof value !== 'number' || !Number.isFinite(value)) {
    return 0;
  }
  return Math.max(0, value);
}