All files / core timers.ts

100% Statements 10/10
100% Branches 2/2
100% Functions 5/5
100% Lines 9/9

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                                      179x 255x 255x   179x   2x     27x 27x   17x 17x                
/** Owns one replaceable timeout and exposes deterministic idempotent cleanup. @internal */
export interface TimeoutManager {
  /** Replaces any pending callback and schedules the next callback after `delay` milliseconds. */
  schedule(callback: () => void, delay: number): void;
  /** Cancels the pending callback. Repeated calls are no-ops. */
  clear(): void;
  /** Whether a callback is currently pending. */
  readonly pending: boolean;
}
 
/**
 * Creates the timeout primitive shared by delayed overlays and typeahead buffers.
 *
 * @remarks A fired callback releases its timer before invoking consumer code, so re-entrant
 * scheduling is safe. The manager never reads DOM globals and can be disposed with `clear()`.
 * @internal
 */
export function createTimeoutManager(): TimeoutManager {
  let timer: ReturnType<typeof setTimeout> | undefined;
  const clear = (): void => {
    if (timer !== undefined) clearTimeout(timer);
    timer = undefined;
  };
  return {
    get pending() {
      return timer !== undefined;
    },
    schedule(callback, delay) {
      clear();
      timer = setTimeout(
        () => {
          timer = undefined;
          callback();
        },
        Math.max(0, delay),
      );
    },
    clear,
  };
}