8000 GitHub - Richienb/p-throttle: Throttle promise-returning & async functions
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

Throttle promise-returning & async functions

License

Notifications You must be signed in to change notification settings

Richienb/p-throttle

 
 

Repository files navigation

p-throttle

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 throttled function is only called twice a second:

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

const now = Date.now();

const throttle = pThrottle({
	limit: 2,
	interval: 1000
});

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

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(options)

Returns a throttle function.

Returns a throttled version of fn.

options

Type: object

Both the limit and interval options must be specified.

limit

Type: number

Maximum number of calls within an interval.

interval

Type: number

Timespan for limit in milliseconds.

throttle(function_)

function_

Type: Function

Promise-returning/async function or a normal function.

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…

About

Throttle promise-returning & async functions

Resources

License

Code of conduct

Stars

Watchers

Forks

Sponsor this project

Packages

No packages published

Languages

  • JavaScript 79.6%
  • TypeScript 20.4%
0