← All items

Frame scheduler

primitive · T1 · v1.0.0 · ready

About

Every JS driver schedules its work here: measurements run before DOM writes in each frame, so drivers never force a synchronous layout. Idle when nothing is scheduled.

Layers

Static
n/a: no visual output.

Accessibility

n/a: callers decide whether to schedule work.

Sources

  • original

Code

Download zip

Self-contained: copy every file, keeping the folder structure.

scheduler.ts
// web-effects frame-scheduler 1.0.0 · MIT-0
// Shared animation-frame scheduler (D3.9). One requestAnimationFrame loop for every caller.
// Each frame runs all `read` callbacks, then all `write` callbacks, so DOM measurements and
// DOM writes never interleave (no forced synchronous layout). Hidden tabs pause it for free,
// because browsers stop requestAnimationFrame there. Pausing off-screen work is the caller's job.

export type FrameTask = {
  /** Measure the DOM. Runs before every write of the same frame. */
  read?: (time: number) => void;
  /** Mutate the DOM (styles, custom properties). */
  write?: (time: number) => void;
};

export type FrameScheduler = {
  /** Runs `task` every frame until the returned function is called. */
  loop: (task: FrameTask) => () => void;
  /** Runs `task` once, on the next frame. Requesting a pending task again is a no-op. */
  once: (task: FrameTask) => () => void;
};

type FrameApi = {
  request: (callback: (time: number) => void) => number;
  cancel: (handle: number) => void;
};

// Resolved per call, not at import, so importing this module is safe during server rendering.
const browserFrames: FrameApi = {
  request: (callback) => requestAnimationFrame(callback),
  cancel: (handle) => cancelAnimationFrame(handle),
};

export function createScheduler(
  frames: FrameApi = browserFrames,
): FrameScheduler {
  const looping = new Set<FrameTask>();
  const pending = new Set<FrameTask>();
  let handle: number | null = null;

  const tick = (time: number) => {
    handle = null;
    const tasks = [...looping, ...pending];
    pending.clear();
    for (const task of tasks) task.read?.(time);
    for (const task of tasks) task.write?.(time);
    if (looping.size > 0 || pending.size > 0) handle = frames.request(tick);
  };

  const start = () => {
    if (handle === null) handle = frames.request(tick);
  };

  const stopIfIdle = () => {
    if (handle !== null && looping.size === 0 && pending.size === 0) {
      frames.cancel(handle);
      handle = null;
    }
  };

  return {
    loop(task) {
      looping.add(task);
      start();
      return () => {
        looping.delete(task);
        stopIfIdle();
      };
    },
    once(task) {
      pending.add(task);
      start();
      return () => {
        pending.delete(task);
        stopIfIdle();
      };
    },
  };
}

/** The scheduler every primitive shares. */
export const frameScheduler: FrameScheduler = createScheduler();