Skip to content

Commit

Permalink
Cleans up implementation of referencing
Browse files Browse the repository at this point in the history
  • Loading branch information
arjunmehta committed Nov 18, 2016
1 parent fd40fc5 commit fa61fff
Showing 1 changed file with 16 additions and 11 deletions.
27 changes: 16 additions & 11 deletions lib/heart.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', {
Expand All @@ -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);
}
}

Expand Down Expand Up @@ -133,27 +133,26 @@ 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);
}
};

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++) {
Expand All @@ -167,6 +166,12 @@ function createInterval(heart) {
};
}

function unreference(heart) {
if (heart.interval.unref) {
heart.interval.unref();
}
}


module.exports = {
initialize: initialize
Expand Down

0 comments on commit fa61fff

Please sign in to comment.