Skip to content
Throttle promise-returning & async functions
Branch: master
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Type Name Latest commit message Commit time
Failed to load latest commit information.
.editorconfig Meta tweaks and drop Node.js 4 (#8) Aug 29, 2018
.gitattributes Meta tweaks Sep 17, 2018
.gitignore Meta tweaks Sep 17, 2018
.npmrc
.travis.yml Meta tweaks and drop Node.js 4 (#8) Aug 29, 2018
index.d.ts Refactor TypeScript definition to CommonJS compatible export (#17) Apr 6, 2019
index.js Refactor TypeScript definition to CommonJS compatible export (#17) Apr 6, 2019
index.test-d.ts Refactor TypeScript definition to CommonJS compatible export (#17) Apr 6, 2019
license Meta tweaks and drop Node.js 4 (#8) Aug 29, 2018
package.json 3.1.0 Apr 6, 2019
readme.md
test.js Meta tweaks Feb 20, 2019

readme.md

p-throttle Build Status

Throttle promise-returning & async functions

It also works with normal functions.

Useful for rate limiting calls to an external API, for example.

Install

$ npm install p-throttle

Usage

Here, the trottled function is only called twice a second:

const pThrottle = require('p-throttle');

const now = Date.now();

const throttled = pThrottle(index => {
	const secDiff = ((Date.now() - now) / 1000).toFixed();
	return Promise.resolve(`${index}: ${secDiff}s`);
}, 2, 1000);

for (let i = 1; i <= 6; i++) {
	throttled(i).then(console.log);
}
//=> 1: 0s
//=> 2: 0s
//=> 3: 1s
//=> 4: 1s
//=> 5: 2s
//=> 6: 2s

API

pThrottle(fn, limit, interval)

Returns a throttled version of fn.

fn

Type: Function

Promise-returning/async function or a normal function.

limit

Type: number

Maximum number of calls within an interval.

interval

Type: number

Timespan for limit in milliseconds.

throttledFn.abort()

Abort pending executions. All unresolved promises are rejected with a pThrottle.AbortError error.

Related

  • p-debounce - Debounce promise-returning & async functions
  • p-limit - Run multiple promise-returning & async functions with limited concurrency
  • p-memoize - Memoize promise-returning & async functions
  • More…

License

MIT © Sindre Sorhus

You can’t perform that action at this time.