Skip to content

Usage

Interpolation between A and B is most often done over time. For example, move an element to a position over a period of two seconds.

One way of doing this is by repeatedly calling interpolate, but with an incrementing interpolation amount.

A rough example might be:

let position = 0; // Start of position of interpolation
const run = () => {
const v = interpolate(position, a, b);
// Omitted: do something with v
position += 0.01; // Move along range a little
if (position <= 1) setTimeout(run, 100); // If there's more to go, loop
};
run(); // trigger

In the above example, we step a little further (1%) in the interpolation range every 100ms. The problem with this approach is if you change your mind about how often it should compute, you’ll need to adjust the interpolation amount to get a similar outcome. And plus there are a lot more things to handle to retrigger the interpolation etc.

What we want is some higher-level machinery to intermingle time with interpolation and take care of the boring things for us.

Interval-based

Numbers.interpolatorInterval will run from A to B over the provided time interval.

When you call it, you provide the A and B values as usual, but now the interpolation amount is determined by the interval.

// Returns a function to to interpolate from 125 -> 678 over 5 seconds
const compute = interpolatorInterval({ secs: 5 }, 125, 678);

The returned function can be called whenever you need to compute the current value of the interpolator.

For example:

// Create the interpolator
const compute = interpolatorInterval({ secs: 5 }, 125, 678);
// Use it within a loop
const loop = () => {
const v = compute(); // Get the current value of interpolator
// Omitted: do other stuff in our loop...
window.requestAnimationFrame(loop)
}

The interpolator starts when first created. To reset it, simply create it again.

If A & B values are omitted, you’ll get a function that interpolates between 0..1

// Function that computes values from 0..1 over one minute
const compute = interpolatorInterval({ mins: 1});

Stepped-based

Numbers.interpolatorStepped returns a function that progresses through the interpolation range manually.

In most cases the aforementioned interpolatorInterval is preferred over interpolatorStepped. The stepped variant is when you specifically do not want to tie the interpolation to clock time.

The first parameter is how much to increment the interpolation amount with each step. In the below example, interpolation amount steps from 0..1 with increments of 0.1. The calculated interpolation amount is used to interpolating between the value range of 100-200.

const compute = interpolatorStepped(0.1, 100, 200);

As with the interval-based interpolator, the returned function is called to calculate the value.

let value = compute();

Each time compute() is called, the interpolator progresses until it reaches 1 (ie. 100%). If you keep calling compute(), it will return the final (B) value.