-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
66 lines (59 loc) · 1.33 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
'use strict'
const EventEmitter = require('events')
const debug = require('debug')('heartbeat')
/**
* follow num is default if not set
* opts: {
* interval: 30
* timeout: 2
* }
*/
module.exports = (opts) => {
return new Heartbeat(opts)
}
class Heartbeat extends EventEmitter {
constructor (opts) {
super()
opts = opts || {}
this.interval = +opts.interval || 30
this.timeout = +opts.timeout || 2
this.intervalTimer = null
this.timeoutCurrentCount = 0
this.timeoutTimer = null
this.init()
}
init () {
this.on('pong', () => {
this.timeoutCurrentCount = 0
})
this.on('ping', () => {
this.timeoutCurrentCount++
})
}
start () {
this.intervalTimer = setInterval(() => {
//if timeout count more than setting, emit timeout and stop heartbeat
debug(`${this.timeoutCurrentCount} ping`)
if(this.timeoutCurrentCount > this.timeout) {
this.emit('timeout')
this.stop()
return
}
this.emit('ping')
}, this.interval * 1000)
}
stop () {
clearInterval(this.intervalTimer)
}
restart () {
this.stop()
this.start
}
changeInterval (interval) {
if(isNaN(interval) || interval < 1) {
throw new TypeError('interval is NaN or less than 1')
}
this.interval = interval
this.restart()
}
}