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

@ambassify/throttle

v3.0.1

Published

Throttle depending on function arguments.

Downloads

862

Readme

Throttle

CircleCI

Create a throttled version of a function.

Installation

npm install --save @ambassify/throttle

Usage

Creates a throttled version of func. func will only be invoked when its result is not in the throttled function's cache or the time between the current and last invocation is larger than what's specified by delay.

If func is async, the throttled function will immediately return a value from cache (if available) while func is executing.

Returns: ThrottledFunction - The throttled version of "func"

| Param | Type | Description | | --- | --- | --- | | func | function | The function to throttle | | options | ThrottleOptions | |

Example

const throttle = require('@ambassify/throttle');

const throttled = throttle(<function-to-throttle>, <options>);

throttled('hello');
throttled.clear(<...args>);

ThrottleOptions : Object

| Name | Type | Description | | --- | --- | --- | | delay | number | How much time must have been elapsed for func to be invoked again when there's a chached result available. Defaults to Infinity. | | maxAge | number | How long are items allowed to remain in cache. Unlimited by default. | | maxSize | number | How long are items allowed to remain in cache. Unlimited by default. | | cache | Map | Specify a custom cache for throttle to use. Must provide methods that match Map's equivalent: has, get, set, delete, clear | | resolver | function | Given the same arguments used to invoke func return only what's important to build the cache key. | | onUpdated | function | Invoked with the cacheItem whenever the item is updated. | | onError | 'clear' | 'cached' | 'persist' | function | Error handler to use when "func" throws or rejects. - clear: The cache is cleared and the error is thrown - persist: The error is saved into cache and thrown - cached: If a previous value is in cache, it will be returned, if not the error will be thrown - a custom function that receives the error as first param and cacheItem as the second, when specified the throttled function won't touch the cache when an error occurs, it's up to this handler to interact with cacheItem. |

ThrottledFunction : function

The throttled function.

Properties

| Name | Type | Description | | --- | --- | --- | | clear | function | When invoked without any arguments the entire cache is cleared, when are supplied they are passed, the item for those arguments is removed from cache. |

CacheItem

CacheItems are exposed through the onUpdated callback that can be specified in the throttle options.

  • cacheItem.initialized: Whether or not the item has its initial value
  • cacheItem.pending: The pending promise when throttle is currently running but already has a previous value
  • cacheItem.key: The key for this cache item
  • cacheItem.stale: Whether or not the cache item's value is considered stale based on the last time it was updated and its "delay" option.
  • cacheItem.value: Current value of the cache item. When this is set, all timers and the like for the item are also reset
  • cacheItem.error: Same as "value" but used to indicate the result of throttled is an error
  • cacheItem.clear(): Clear the item from throttled's cache
  • cacheItem.delay(delay): Update this specific item's "delay"
  • cacheItem.maxAge(maxAge): Update this specific item's "maxAge"

Example

const throttle = require('@ambassify/throttle');

let example = 0;

async function myFunction(input) {
    // Delay 500 ms to fake a slow operation
    await new Promise(resolve => setTimeout(resolve, 500));

    example += input;
    return example;
}

// Allow `myFunction` to be called once every 2 seconds for each different
//`input` and cache the value for max 5 seconds.
const throttled = throttle(myFunction, { delay: 2000, maxAge: 5000 });

throttled(1); // 1
throttled(1); // 1
throttled(1); // 1

// Wait for 2 seconds
// "myFunction" is called, but the old cached result is returned immediately

throttled(1); // 1

// Wait 500ms (the fake delay)
// "myFunction" isn't called (as delay hasn't been reached) but we do get the
// latest result

throttled(1); // 2

// Wait for 5 seconds
// "myFunction" is called but the old cached value has expired so it resolves
// with the new value once the function has run

throttled(1); // 3

const conditional = throttle(myFunction, {
    delay: 2000,
    maxAge: 5000
    onCached: function(item) {
        // Only cache results for large values of input
        if (item.key < 10)
            item.clear();
    }
}

conditional(1); // 1
conditional(1); // 2
conditional(1); // 3

conditional(20); // 23
conditional(20); // 23

Contributing

If you have some issue or code you would like to add, feel free to open a Pull Request or Issue and we will look into it as soon as we can.

License

We are releasing this under a MIT License.

About us

If you would like to know more about us, be sure to have a look at our website, or our Twitter accounts @Ambassify, Sitebase, JorgenEvens.