Skip to content

Elapsed

You might want to modulate based on a period of time elapsing. As a very simple example, let’s say we want to set the x position of an item according to an elapsed time of five seconds.

Sources.elapsed returns a function which yields a percentage of completion for a time period. That is, when it starts it will yield 0, when the time is halfway up it will return 0.5 all the way through to 1 when the elapsed period has finished.

import { Sources } from 'ixfx/modulation.js';
const time = Sources.elapsed({ secs: 5 });
const animate = () => {
const t = time(); // Get 0..1
// Apply to pixel coordinates, relative to screen width
el.style.left = `${t*window.innerWidth}px`;
window.requestAnimationFrame(animate);
}

By default, Sources.elapsed loops, so you’ll get a series of 0..1 values continually. Use the oneShot option to disable this.

const time = Sources.elapsed({ secs: 5 }, { oneShot: true });

It’s also possible to start the timer at a fixed or relative amount:

// Start 1 second (1/5th) of the way in
const time = Sources.elapsed({ secs: 5 }, { startAt: 1000 });
// Start 50% in
const time = Sources.elapsed({ secs: 5 }, { startAtRelative: 0.5 });

Driving other modulations

A more common use of elapsed (and friends) is to be the ‘driver’ of some other kind of modulation.

For example, at their most basic, an easing function is something that takes an input value and return an ‘eased’ version of it. Easing functions don’t have anything to do with time, even though that’s a common way we want to use them: ‘easing’ to a target value over time. elapsed helps us have a timeline for an easing.

import { Easings, Sources } from 'ixfx/modulation.js';
const easer = Easings.Named.arch; // Yields: (number) => number
const timeline = Sources.elapsed({ secs: 5 }); // Yields: () => number
const loop => {
// Get % of time completion
const t = timeline();
// Use this as the value to ease
const v = easer(t);
// Do something fun with 'v' now that it's non-linear...
window.requestAnimationFrame(loop);
}
loop();

Because elapsed lets us control the starting point, one practical use case is allowing an easing function to start at some arbitrary place.

Friends

Sources.elapsed has some friends that follow the same concept but with different units of time/progression.

Here’s an example

import { Sources } from 'ixfx/modulation.js';
const timeline = Sources.bpm(60); // Yields: () => number
const loop => {
// Get % of time completion
const t = timeline();
window.requestAnimationFrame(loop);
}
loop();