Files: b9dcc7d4908103b141bd9701cec47b3eebd64d2b / watch-throttle.js
910 bytesRaw
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 () {} |
42 |
Built with git-ssb-web