Skip to content

Minimum Rate

Flow.rateMinimum ensures that a function gets called at a minimum rate.

The basic usage looks like:

1
const rm = rateMinimum({
2
interval: 1000; // At least every second
3
whatToCall: (args) => {
4
// Do something every one second
5
}
6
fallback:() => {
7
// return a value when there is a timeout
8
return 20;
9
}
10
})
11
12
// Trigger it once with value 10
13
rm(10);

On line 1 we invoke rateMinimum, getting back a function, rm to call with a value. We’d call this whenever we have a value to process. The value gets passed to the whatToCall function provided on line 3.

Now, if we don’t call rm at least every second, rateMinimum will call the fallback function (line 6) to generate a value and provides it to whatToCall.

In other words, the whatToCall function gets called at least every second, with either a value that’s passed in when we invoke rm, or using a generated fallback value.

Practical case

Let’s say for example you want to do something based on the speed of the pointer movement. One way to calculate speed is to recalculate based on total travel and current elapsed time. You can easily use the pointermove event to have a function called when the pointer moves, but there’s not an event for when the pointer is not moving.

import { rateMinimum } from "https://unpkg.com/ixfx/dist/flow.js"
import { movingAverageLight } from 'https://unpkg.com/ixfx/dist/numbers.js';
// Average distances
const average = movingAverageLight();
const rm = rateMinimum({
interval: { secs: 1 },
// Gets distance, adds to average
whatToCall: (distance: number) => {
average(distance);
},
// If there are no pointermove events, distance is 0
fallback() {
return 0;
}
})
// Calculate movement
document.addEventListener(`pointermove`, event => {
rm(event.movementX + event.movementY);
});