diff --git a/lib/heart.js b/lib/heart.js index 56dd327..340e6f7 100644 --- a/lib/heart.js +++ b/lib/heart.js @@ -25,9 +25,7 @@ function Heart(heartrate, name) { this.interval = setInterval(createInterval(this), heartrate); - if (this.interval.unref) { - this.interval.unref(); - } + unreference(this); } Object.defineProperty(Heart.prototype, 'age', { @@ -47,10 +45,12 @@ Object.defineProperty(Heart.prototype, 'name', { Heart.prototype.setHeartrate = function(heartrate) { if (heartrate) { this.heartrate = heartrate; + clearInterval(this.interval); this.interval = setInterval(createInterval(this), heartrate); - if (this.interval.unref) { - this.interval.unref(); + + if (this.events.length === 0) { + unreference(this); } } @@ -133,12 +133,12 @@ Heart.prototype.killEvent = function(name, beatevent) { idx = this.events.indexOf(beatevent); } - if(idx > -1){ + if (idx > -1) { this.events.splice(idx, 1); } - if(this.events.length === 0 && this.interval.unref){ - this.interval.unref(); + if (this.events.length === 0) { + unreference(this); } }; @@ -146,14 +146,13 @@ Heart.prototype.killAllEvents = function() { this.events = []; this.eventList = {}; - if (this.interval.unref) { - this.interval.unref(); - } + unreference(this); }; function createInterval(heart) { return function() { var events = heart.events; + heart.heartbeat++; for (var i = 0; i < events.length; i++) { @@ -167,6 +166,12 @@ function createInterval(heart) { }; } +function unreference(heart) { + if (heart.interval.unref) { + heart.interval.unref(); + } +} + module.exports = { initialize: initialize