path-rite

springSettled

Check if a spring has settled close enough to its target with negligible velocity.

springSettled(current: number, velocity: number, target: number, precision: number): boolean

current — Current position of the spring.

velocity — Current velocity.

target — The target equilibrium position.

precision — Threshold for both position and velocity. The spring is settled when |current - target| < precision and |velocity| < precision.

Returnstrue if the spring is at rest, false if it should keep animating.

Use this as the stop condition in your animation loop. A precision of 0.01 works well for most pixel-based animations.

// Stop the loop when settled
function animate() {
  const state = springStep(current, velocity, target, 170, 26, 1, 1/60);
  current = state.value;
  velocity = state.velocity;

  element.style.opacity = current;

  if (!springSettled(current, velocity, target, 0.01)) {
    requestAnimationFrame(animate);
  }
}