Skip to content

pingpongStep

pingpongStep(current, delta, max): PingpongStep

Defined in: pingpong-step.ts:39

Moves a position along a line and bounces it off both ends — the motion of a pendulum, a loading indicator sweeping back and forth, or a value cycling through a range without jumping.

Call it once per frame or tick, feeding the returned value back in as current and multiplying your step size by the returned direction. That one returned sign is what saves the caller from tracking the bounce itself.

Reaching or passing either end clamps to that end and flips the direction, so the position can never escape [0, max] however large delta is. A single overshooting step therefore loses the excess rather than reflecting it.

O(1) time; allocates one small object per call, so hoist the destructuring rather than the call if this runs per element.

number

Where the position is now, within [0, max].

number

How far to move; the sign sets the direction of travel.

number

The upper end of the line. The lower end is always 0.

PingpongStep

The new position and the direction for the next step.

let { value, direction } = { value: 8, direction: 1 as 1 | -1 };
({ value, direction } = pingpongStep(value, 3 * direction, 10));
// value: 10, direction: -1 — hit the end and turned round
({ value, direction } = pingpongStep(value, 3 * direction, 10));
// value: 7, direction: -1
```;