git ssb

1+

Matt McKegg / mutant



Tree: 4f9e58ce423d145b70980a342e93dbbffbbc95f6

Files: 4f9e58ce423d145b70980a342e93dbbffbbc95f6 / watch-throttle.js

1063 bytesRaw
1var resolve = require('./resolve')
2var isObservable = require('./is-observable')
3
4module.exports = function throttledWatch (obs, minDelay, listener, opts) {
5 var throttling = false
6 var lastRefreshAt = 0
7 var lastValueAt = 0
8 var throttleTimer = null
9
10 var broadcastInitial = !opts || opts.broadcastInitial !== false
11
12 // default delay is 20 ms
13 minDelay = minDelay || 20
14
15 // run unless opts.broadcastInitial === false
16 if (broadcastInitial) {
17 listener(resolve(obs))
18 }
19
20 if (isObservable(obs)) {
21 return obs(function (v) {
22 if (!throttling) {
23 if (Date.now() - lastRefreshAt > minDelay) {
24 refresh()
25 } else {
26 throttling = true
27 throttleTimer = setInterval(refresh, minDelay)
28 }
29 }
30 lastValueAt = Date.now()
31 })
32 } else {
33 return noop
34 }
35
36 function refresh () {
37 lastRefreshAt = Date.now()
38 listener(obs())
39 if (throttling && lastRefreshAt - lastValueAt > minDelay) {
40 throttling = false
41 clearInterval(throttleTimer)
42 }
43 }
44}
45
46function noop () {}
47

Built with git-ssb-web