使用一个函数进行一系列调用以返回一个结果,该结果在 Angular 模板中一次被请求多次。在这些请求期间,结果不会改变,因此在函数内部进行额外调用的开销是不必要的。
是否可以创建一个在特定等待时间内缓存并返回相同结果的节流函数?
按照下面的简化示例。
var throttleCache = _.memoizeThrottle(function() {
return _.now();
}, 100);
_.delay(throttleCache, 0); // now + 0ms
_.delay(throttleCache, 10); // now + 0ms
_.delay(throttleCache, 99); // now + 0ms
_.delay(throttleCache, 101); // now + 101ms
_.delay(throttleCache, 150); // now + 101ms
据我所知,_.memoize
根据参数无限期地缓存结果,看不到每隔一段时间自动刷新此缓存的方法。而_.throttle
和_.debounce
只在设置的约束内触发函数,不返回包含函数的输出。
最佳答案
我使用 _.memoize 方法对其进行扩展并添加一个 ttl 参数,以在过期时强制重新计算值。
#!/usr/bin/env coffee
_=require 'underscore'
# Memoize an expensive function by storing its results.
# After ttl time, the value will be recomputed
memoinesic = (func, hasher=_.identity, ttl=0)->
memoize = ()->
cache = memoize.cache
key = hasher.apply(@,arguments)
now = Date.now()
if !_.has(cache,key) or now>cache[key].expires
cache[key] =
value: func.apply(@,arguments)
expires: now+ttl
cache[key].value
memoize.cache = {}
memoize
_.mixin(memoinesic:memoinesic)
# Let's try it!
appendToNow = _.memoinesic(
(x)-> "#{x}:#{Date.now()}",
null,
1000
)
logTimedFoo = _.compose console.log,_.partial appendToNow,'foo'
logTimedFoo()
setInterval logTimedFoo,200
关于javascript - 结合 _.memoize 和 _.throttle 来限制函数调用并在时间窗口内缓存结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23827691/