All files / kernel-utils/src misc.ts

100% Statements 19/19
100% Branches 8/8
100% Functions 7/7
100% Lines 18/18

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                112x 230x 230x 537x 537x                   112x 111x                         47x 2x   45x 2x   43x 43x 43x 4x 4x   43x 5x        
import { AbortError } from '@metamask/kernel-errors';
 
/**
 * A simple counter which increments and returns when called.
 *
 * @param start - One less than the first returned number.
 * @returns A counter.
 */
export const makeCounter = (start: number = 0) => {
  let counter: number = start;
  return () => {
    counter += 1;
    return counter;
  };
};
 
/**
 * Delay execution by the specified number of milliseconds.
 *
 * @param ms - The number of milliseconds to delay.
 * @returns A promise that resolves after the specified delay.
 */
export const delay = async (ms = 1): Promise<void> =>
  new Promise((resolve) => setTimeout(resolve, ms));
 
/**
 * Abortable sleep.
 *
 * @param ms - The number of milliseconds to sleep.
 * @param signal - The abort signal to listen to.
 * @returns A promise that resolves when the sleep is complete.
 */
export async function abortableDelay(
  ms: number,
  signal?: AbortSignal,
): Promise<void> {
  if (ms <= 0) {
    return;
  }
  if (signal?.aborted) {
    throw new AbortError();
  }
  await new Promise<void>((resolve, reject) => {
    const id = setTimeout(resolve, ms);
    const onAbort = (): void => {
      clearTimeout(id);
      reject(new AbortError());
    };
    if (signal) {
      signal.addEventListener('abort', onAbort, { once: true });
    }
  });
}