Skip to content

frameLoop

Calls onFrame once per animation frame with the time elapsed since the start, until it returns false or the loop is cancelled: the engine behind tween, for anything that moves on its own clock (a spring played with at(elapsedMs), a physics step, a progress counter).

The first call happens right away, with 0, so the first state is drawn before the next paint. Frames come from requestAnimationFrame, or a 16 ms timer where it does not exist (Node.js, some workers).

Available since v3.1.5

import { frameLoop } from '@helpers4/animation';
// or, from the all-in-one package (same code, one install):
import { frameLoop } from 'helpers4/animation';
frameLoop(onFrame: function, options: FrameLoopOptions): FrameLoop
ParameterTypeDescription
onFramefunctionReceives the elapsed milliseconds; return `false` to stop
optionsFrameLoopOptionsClock and cancellation — see FrameLoopOptions

FrameLoop — A FrameLoop, to cancel it or await its end

Return false from onFrame to stop; finished then resolves with true.

const bounce = spring({ damping: 8 });
await frameLoop((elapsed) => {
  ball.style.translate = `0 ${bounce.at(elapsed) * 200}px`;
  return elapsed < bounce.durationMs;
}).finished;

cancel() stops it; finished resolves with false.

const loop = frameLoop(drawFrame);
loop.cancel();

A running frameLoop.

interface FrameLoop {
  finished: Promise<boolean>;
  cancel(): void;
}

Options for frameLoop.

interface FrameLoopOptions {
  now?: function;
  signal?: AbortSignalLike;
}

View source on GitHub