All files / src/schedulers asyncScheduler.ts

100% Statements 20/20
100% Branches 5/5
100% Functions 3/3
100% Lines 20/20

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                            2x 18x 18x 18x 7x 9x 9x 9x 9x 1x 1x 9x 7x 7x   18x 11x 11x 11x   18x 18x  
import { type Scheduler, type SchedulerFlush, type SchedulerTask } from "./interface";
 
/**
 * Creates an async {@link Scheduler}.
 * @param defer - A function that defers the execution of the {@link SchedulerFlush} function.
 * @returns A {@link Scheduler}
 *
 * @example
 * ```ts
 * import { asyncScheduler } from "@embra/reactivity";
 * const MicroTaskScheduler = asyncScheduler(flush => Promise.resolve().then(flush));
 * const AnimationFrameScheduler = asyncScheduler(requestAnimationFrame);
 * ```
 */
export const asyncScheduler = (defer: (flush: SchedulerFlush) => unknown): Scheduler => {
  let tasks: Set<SchedulerTask>;
  let pending: boolean | undefined;
  const flush = (): void => {
    for (const task of tasks) {
      tasks.delete(task);
      try {
        task.schedulerTask_(AsyncScheduler);
      } catch (e) {
        console.error(e);
      }
    }
    pending = false;
  };
 
  const AsyncScheduler: Scheduler = (task: SchedulerTask): void => {
    (tasks ??= new Set()).add(task);
    pending ||= (defer(flush), true);
  };
 
  return AsyncScheduler;
};