|
47 | 47 |
|
48 | 48 | 'use strict';
|
49 | 49 |
|
50 |
| -var inherits = require('util').inherits; |
51 | 50 | var EventEmitter = require('events').EventEmitter;
|
52 | 51 |
|
53 | 52 | // Exported so that we can mess with it in tests
|
54 | 53 | module.exports.UNITS_TO_MS = 1000;
|
55 | 54 |
|
56 |
| -function Heart(interval, checkSend, checkRecv) { |
57 |
| - EventEmitter.call(this); |
58 |
| - this.interval = interval; |
| 55 | +class Heart extends EventEmitter { |
| 56 | + constructor (interval, checkSend, checkRecv) { |
| 57 | + super(); |
59 | 58 |
|
60 |
| - var intervalMs = interval * module.exports.UNITS_TO_MS; |
61 |
| - // Function#bind is my new best friend |
62 |
| - var beat = this.emit.bind(this, 'beat'); |
63 |
| - var timeout = this.emit.bind(this, 'timeout'); |
| 59 | + this.interval = interval; |
64 | 60 |
|
65 |
| - this.sendTimer = setInterval( |
66 |
| - this.runHeartbeat.bind(this, checkSend, beat), intervalMs / 2); |
| 61 | + var intervalMs = interval * module.exports.UNITS_TO_MS; |
| 62 | + // Function#bind is my new best friend |
| 63 | + var beat = this.emit.bind(this, 'beat'); |
| 64 | + var timeout = this.emit.bind(this, 'timeout'); |
67 | 65 |
|
68 |
| - // A timeout occurs if I see nothing for *two consecutive* intervals |
69 |
| - var recvMissed = 0; |
70 |
| - function missedTwo() { |
71 |
| - if (!checkRecv()) return (++recvMissed < 2); |
72 |
| - else { recvMissed = 0; return true; } |
| 66 | + this.sendTimer = setInterval( |
| 67 | + this.runHeartbeat.bind(this, checkSend, beat), intervalMs / 2); |
| 68 | + |
| 69 | + // A timeout occurs if I see nothing for *two consecutive* intervals |
| 70 | + var recvMissed = 0; |
| 71 | + function missedTwo () { |
| 72 | + if (!checkRecv()) |
| 73 | + return (++recvMissed < 2); |
| 74 | + else { recvMissed = 0; return true; } |
| 75 | + } |
| 76 | + this.recvTimer = setInterval( |
| 77 | + this.runHeartbeat.bind(this, missedTwo, timeout), intervalMs); |
73 | 78 | }
|
74 |
| - this.recvTimer = setInterval( |
75 |
| - this.runHeartbeat.bind(this, missedTwo, timeout), intervalMs); |
76 |
| -} |
77 |
| -inherits(Heart, EventEmitter); |
78 | 79 |
|
79 |
| -module.exports.Heart = Heart; |
| 80 | + clear () { |
| 81 | + clearInterval(this.sendTimer); |
| 82 | + clearInterval(this.recvTimer); |
| 83 | + } |
80 | 84 |
|
81 |
| -Heart.prototype.clear = function() { |
82 |
| - clearInterval(this.sendTimer); |
83 |
| - clearInterval(this.recvTimer); |
84 |
| -}; |
| 85 | + runHeartbeat (check, fail) { |
| 86 | + // Have we seen activity? |
| 87 | + if (!check()) |
| 88 | + fail(); |
| 89 | + } |
| 90 | +} |
85 | 91 |
|
86 |
| -Heart.prototype.runHeartbeat = function(check, fail) { |
87 |
| - // Have we seen activity? |
88 |
| - if (!check()) fail(); |
89 |
| -}; |
| 92 | +module.exports.Heart = Heart; |
0 commit comments