Skip to content

Commit

Permalink
Refactor interval to use setTimeout instead of setInterval
Browse files Browse the repository at this point in the history
  • Loading branch information
mauricioschneider committed Feb 10, 2015
1 parent 703ccbb commit 5e24f54
Showing 1 changed file with 34 additions and 24 deletions.
58 changes: 34 additions & 24 deletions lib/agent/plugins/control-panel/interval/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ var parse_cmd = function(str) {
if (hooks)
hooks.trigger('error', new Error('Invalid command: ' + str));
}
}
};

var request = function() {
if (requesting)
Expand All @@ -45,20 +45,16 @@ var request = function() {
resp.body.forEach(function(el) {
var cmd = el.target ? el : parse_cmd(el);
if (cmd) emitter.emit('command', cmd);
})
})
}
});

var load_hooks = function() {
// whenever device connects, send a request
hooks.on('connected', request);

// whenever reachable state changes, hasten or slowen
bus.on('reachable', set_interval);
bus.on('unreachable', set_faster_interval);
schedule_request();
});
};

loaded = true;
}
var schedule_request = function (custom_delay) {
var delay = custom_delay || current_delay;
timer = setTimeout(request, delay);
};

// set timer to check on intervals
var set_interval = function(delay) {
Expand All @@ -69,33 +65,47 @@ var set_interval = function(delay) {
current_delay = delay;

logger.info('Queuing check-ins every ' + delay/60000 + ' minutes.');
if (timer) clearInterval(timer);
timer = setInterval(request, delay);
}
if (timer) {
clearTimeout(timer);
schedule_request();
}
};

var set_faster_interval = function() {
set_interval(short_delay);
}
};


var load_hooks = function() {
// whenever device connects, send a request
hooks.on('connected', request);

// whenever reachable state changes, hasten or slowen
bus.on('reachable', set_interval);
bus.on('unreachable', set_faster_interval);

loaded = true;
};

var unload = function(err) {
if (err)
logger.error('Failed, unloading: ' + err.message);

hooks.remove('woken', request);
hooks.remove('connected', request);
if (timer) clearInterval(timer);
if (timer) clearTimeout(timer);

loaded = false;

if (emitter) {
emitter.removeAllListeners();
emitter = null;
}
}
};

exports.check = function() {
request();
}
};

exports.load = function(cb) {
if (emitter)
Expand All @@ -107,13 +117,13 @@ exports.load = function(cb) {

load_hooks();
set_interval();
setTimeout(request, 3000); // wait a bit and fire request
schedule_request(3000); // wait a bit and fire request

emitter = new Emitter;
emitter = new Emitter();
cb(null, emitter);
}
};

exports.unload = function() {
if (!hooks) return; // not loaded yet.
unload();
}
};

0 comments on commit 5e24f54

Please sign in to comment.