npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

throttle-repeat

v2.1.3

Published

Repeatedly executes a given task at a given maximum rate (in milliseconds) until a given condition is true

Downloads

11

Readme

throttle-repeat

npm version CircleCI Coverage Status

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 5

API

throttleRepeat(params) -> Promise<Any>

Required parameters

  • task: function(index) -> Promise<Any>

An action to perform on each iteration. Must be yield-able. Iteration index is passed to the task function.

  • 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 rate function with iterationResult of 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 the rate milliseconds, 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 each task will be called every two seconds. If a task takes 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 task could be instructed to return the actual request count, and rate could 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) -> Boolean

Exit condition. task is called until the condition evaluates as true. The condition is first evaluated after the end of the first call. count is the number of task executions so far, iterationResult is the result of the completed iteration.

Optional parameters

  • reducer: function(accumulator, iterationResult) -> Any
  • initialValue: Any

Applies the reducer function against an accumulator and each iterationResult to reduce it to a single value. initialValue is the initial value of accumulator. reducer defaults to a simple increment, while initialValue defaults to 0.

Returns

  1. By default, returns the number of times task was called.

  2. If reducer and initialValue are specified, returns the most recent value of accumulator.

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
// }