throttle-repeat
Repeatedly executes a given task at a given maximum rate (in milliseconds) until a given condition is true.
Optionally, accepts reducer and initialValue to reduce results of each iteration.
Allows for variable rates (based on the most recent iteration).
Usage
const throttleRepeat = require('throttle-repeat');
return throttleRepeat({
task: (index) => {
console.log(`An async action running every second: ${index}`);
return Promise.resolve(index);
},
rate: () => 1000,
until: (count, iterationResult) => (count === 5 || iterationResult > 10)
})
.then(result => console.log(result));
// returns 5API
throttleRepeat(params) -> Promise<Any>
Required parameters
task:
function(index) -> Promise<Any>An action to perform on each iteration. Must be yield-able. Iteration
indexis passed to thetaskfunction.rate:
function(iterationResult) -> Number (milliseconds)The number of milliseconds between the start of the completed iteration and the start of the next iteration. After each iteration, the module invokes the
ratefunction withiterationResultof the completed iteration and computes the waiting time before starting the next iteration according to the formula:<time before next iteration> = <result of rate(...)> - <execution time of the completed iteration>. If completed iteration took more than theratemilliseconds, the next iteration is started immediately upon completion of the iteration.Example 1. Fixed wait time. Just provide a constant value:
rate: () => 2000. This means eachtaskwill be called every two seconds. If atasktakes more than two seconds, the next iteration follows as soon as the most recent task yields, even if it is more than two seconds.Example 2. Variable wait time. A variable-load
taskcould be instructed to return the actual request count, andratecould be defined as something like:rate: (actualRequestCount) => 1000 * actualRequestCount / 20. If 20 requests are sent, it waits for one second. If 10 requests are sent, the wait time is proportionally reduced to half a second. This is useful for tasks like polling a queue (with unknown number of messages) or a database (with unknown number of items) when throttling is important, but waiting for a constant amount of time is sub-optimal.until:
function(count, iterationResult) -> BooleanExit condition.
taskis called until the condition evaluates as true. The condition is first evaluated after the end of the first call.countis the number oftaskexecutions so far,iterationResultis the result of the completed iteration.
Optional parameters
- reducer:
function(accumulator, iterationResult) -> Any initialValue:
AnyApplies the
reducerfunction against anaccumulatorand eachiterationResultto reduce it to a single value.initialValueis the initial value ofaccumulator.reducerdefaults to a simple increment, whileinitialValuedefaults to0.
Returns
By default, returns the number of times
taskwas called.If
reducerandinitialValueare specified, returns the most recent value ofaccumulator.
More examples
Reducer
const throttleRepeat = require('throttle-repeat');
return throttleRepeat({
task: (index) => {
console.log('An async action running every second, five times');
return Promise.resolve(index);
},
rate: () => 1000,
until: (count) => (count === 5),
reducer: (acc, iterationResult) => `${acc},${iterationResult + 1}`,
initialValue: '0'
})
.then(result => console.log(result));
// returns "0,1,2,3,4,5"Advanced (polling a queue)
const throttleRepeat = require('throttle-repeat');
return throttleRepeat({
task: pollMessages.bind(null, QUEUE_URL), // our poller
rate: iterationResult => 1000 * (iterationResult.total / 20), // 20 msg/s
until: (count, iterationResult) =>
iterationResult.total <= 10, // until queue is almost empty
reducer: (accumulator, iterationResult) => {
accumulator.totalProcessed += iterationResult.total;
accumulator.totalSucceeded += iterationResult.succeeded;
return accumulator;
},
initialValue: {
totalProcessed: 0,
totalSucceeded: 0
}
})
.then(result => console.log(result));
// returns {
// totalProcessed: 123
// totalSucceeded: 120
// }