git ssb

1+

Matt McKegg / mutant



Tree: 073f2ca837054c3b04113dd573e1a9e8b0c6ed29

Files: 073f2ca837054c3b04113dd573e1a9e8b0c6ed29 / 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