Skip to content

Elapsed

Module Flow.Elapsed

Elapsed

The Module Flow.Elapsed module has a few functions for tracking passage of time.

An overview:

Since

Elapsed.since yields how much time (in milliseconds) has passed since first invoked. This is the fixed reference point all later invocations are compared to.

import { Elapsed } from "https://unpkg.com/ixfx/dist/flow.js"
// A. Start monitoring elapsed time
const s = Elapsed.since();
// ...some time later ...
s(); // B. Elapsed time since (A)
// ...some time later ...
s(); // C. Elapsed time since (A)

Interval

Elapsed.interval reports the time from the first initialisation and each subsequent call. Unlike since, there is a not a fixed reference point. It is always comparing to either the initial time or when the callback was last run.

import { Elapsed } from "https://unpkg.com/ixfx/dist/flow.js"
// A. Start monitoring elapsed time
const i = Elapsed.interval();
// ...some time later ...
i(); // B. Elapsed time since (A)
// ...some time later ...
i(); // C. Elapsed time since (B)

Once

Elapsed.once fixes both the start point and a second reference time. After initialisation, it records the time at which the first call happens. This is then given as the value for all future calls.

import { Elapsed } from "https://unpkg.com/ixfx/dist/flow.js"
// A. Start monitoring elapsed time
const o = Elapsed.once();
// ...some time later...
o(); // B. Time since (A). Since it is the first call, we now fix the second reference.
// ...some time later...
o(); // C. Will be same value as earlier (B-A)
// ... some time later...
o(); // D. As above, forever

Time completion

If you have a sense of how long something should take, you can track progression.

Flow.ofTotal takes an Interval and returns a function that reports back a 0..1 percentage of completion.

import { ofTotal } from "https://unpkg.com/ixfx/dist/flow.js"
const timer = ofTotal({ mins: 1});
// Every time we call timer() we get the progression
// towards the total duration
timer();

Since we could call the function after the duration has elapsed, it may well return a number over 1. To avoid this, clamp the value:

const timer = ofTotal({ mins: 1}, { clampValue: true });

It’s also possible to wrap the value. When the total duration is exceeded, the progression wraps around back to zero. Therefore, an elapsed time of 150% is reported as 0.5, not 1.5.

const timer = ofTotal({ mins: 1}, { wrapValue: true });