git ssb

1+

Matt McKegg / mutant



Commit 117c25c0033f5aa847498c91de7027643cf61eb7

add throttle and watch-throttle

Matt McKegg committed on 9/10/2016, 6:07:29 AM
Parent: f196fa2114c55fd8d77622666db3b580b0e63e21

Files changed

throttle.jsadded
watch-throttle.jsadded
throttle.jsView
@@ -1,0 +1,36 @@
1+var LazyWatcher = require('./lib/lazy-watcher')
2+var watchThrottle = require('./watch-throttle')
3+var resolve = require('./resolve')
4+
5+module.exports = function Throttle (input, minDelay) {
6+ // default delay is 20 ms
7+ minDelay = minDelay || 20
8+
9+ var binder = LazyWatcher(update, listen, unlisten)
10+ binder.value = resolve(input)
11+ var releases = []
12+
13+ var result = function MutantThrottle (listener) {
14+ if (!listener) {
15+ return binder.getValue()
16+ }
17+ return binder.addListener(listener)
18+ }
19+
20+ function update () {
21+ binder.value = resolve(input)
22+ return true
23+ }
24+
25+ function listen () {
26+ releases.push(watchThrottle(input, minDelay, binder.onUpdate))
27+ }
28+
29+ function unlisten () {
30+ while (releases.length) {
31+ releases.pop()()
32+ }
33+ }
34+
35+ return result
36+}
watch-throttle.jsView
@@ -1,0 +1,41 @@
1+var resolve = require('./resolve')
2+var isObservable = require('./is-observable')
3+
4+module.exports = function throttledWatch (obs, minDelay, listener) {
5+ var throttling = false
6+ var lastRefreshAt = 0
7+ var lastValueAt = 0
8+ var throttleTimer = null
9+
10+ // default delay is 20 ms
11+ minDelay = minDelay || 20
12+
13+ listener(resolve(obs))
14+
15+ if (isObservable(obs)) {
16+ return obs(function (v) {
17+ if (!throttling) {
18+ if (Date.now() - lastRefreshAt > minDelay) {
19+ refresh()
20+ } else {
21+ throttling = true
22+ throttleTimer = setInterval(refresh, minDelay)
23+ }
24+ }
25+ lastValueAt = Date.now()
26+ })
27+ } else {
28+ return noop
29+ }
30+
31+ function refresh () {
32+ lastRefreshAt = Date.now()
33+ listener(obs())
34+ if (throttling && lastRefreshAt - lastValueAt > minDelay) {
35+ throttling = false
36+ clearInterval(throttleTimer)
37+ }
38+ }
39+}
40+
41+function noop () {}

Built with git-ssb-web