git ssb

1+

Matt McKegg / mutant



Tree: dacc7137a972984d5f5adfe48e91c35b8056adb9

Files: dacc7137a972984d5f5adfe48e91c35b8056adb9 / watch-throttle.js

910 bytesRaw
1var resolve = require('./resolve')
2var isObservable = require('./is-observable')
3
4module.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
41function noop () {}
42

Built with git-ssb-web