喉咙
创建函数的节奏版本 .
安装
npm install --save @ambassify/throttle
使用量
创建节奏版本 func。 。 。 . func 将只在其
结果不是在节奏函数的缓存中,也不是在时间之间
当前和最后的引用大于 delay。 。 。 .
若为 func ,节奏函数将立即返回一个值
从缓存( 如果可用) 时 func 执行中.
回返数字 : ThrottledFunction - "func"的节奏版本
| 参数 | 类型 | 说明 |
|---|---|---|
| 乐趣c | function | 节能 |
| 选项 | ThrottleOptions |
示例
const throttle = require('@ambassify/throttle');
const throttled = throttle(<function-to-throttle>, <options>);
throttled('hello');
throttled.clear(<...args>);
旋律选项 : Object
| 名称 | 类型 | 说明 |
|---|---|---|
| 延迟 | number | 还要花多少时间 func 被再次引用 当有 被纠正的结果可用。 默认为 Infinity。 。 。 . |
| 最大年龄 | number | 允许在缓存中保存的物品有多长时间. 默认无限. |
| 最大大小 | number | 允许在缓存中保存的物品有多长时间. 默认无限. |
| 缓存 | Map | 指定用于节流的自定义缓存。 必须提供与地图等同的方法: 已经、 得到、 设定、 删除、 清除 |
| 解析器 | function | 同样的论据 func 仅返回缓存密钥构建中的重要内容 . |
| 已更新 | function | 与声讨 cacheItem 当项目更新时. |
| 错误 | 'clear' | 'cached' | 'persist' | function | 当“ func” 丢出或拒绝时使用错误处理器 。 - clear: 缓存已清除并抛出错误 - persist: 错误被保存到缓存并抛出 - cached: 如果一个先前的值处于缓存中, 它会被返回, 如果错误不会被抛出的话—— 一个自定义函数, 它作为第一个参数接收错误, 而缓存项目作为第二个, 当指定的节奏函数不会在错误发生时触碰缓存时, 由这个处理器来与缓存项目交互 . |
弦乐功能 : function
节奏的功能.
属性
| 名称 | 类型 | 说明 |
|---|---|---|
| 清除 | function | 如果引用时没有任何参数,则整个缓存将被清除 为: 如果这些参数被传递,则这些参数的项目将被从缓存中删除. |
缓存项目
缓存项目通过 onUpdated 在节流阀选项中可以指定的回调.
- 缓存项目。 初始化: 项目是否具有初始值
- 缓存项目。 待定: 当节流阀正在运行但已经存在时, 尚未兑现的承诺 上一数值
- 缓存项目. key: 此缓存项的密钥
- 缓存项目. stale: 缓存项的值是否根据 上次更新和“延迟”选项.
- 缓存项目.值: 缓存项的当前值。 当这个设定,所有的计时器之类的 重设此项目
- 缓存项目. error: 与"值"相同,但用于表示被节制的结果是一个错误
- 缓存项目. clear (): 将项目从节流器的缓存中清除
- 缓存项目. 延迟( 延迟): 更新此特定项目的"延迟"
- 缓存项目.max Age( 最大年龄): 更新此特定项目的"maxAge"
示例
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
捐款
如果你有一些问题或代码,你想添加, 请随意打开一个拉请求或问题 我们会尽快调查.
许可证
我们要用麻省理工学院的许可放出这个.
关于我们
如果你想知道更多关于我们的事 请看看 我们的网站,或者我们的Twitter账户 @ 发音, (中文(简体) ), 场地基地, (中文(简体) ), 豪尔根 Evens。 。 。 .