Reputation: 904
I have the following function:
function monitorClimate() {
var sensorReadingInterval;
function startClimateMonitoring(interval) {
sensorReadingInterval = setInterval(function() {
io.emit('sensorReading', {
temperature: sensor.getTemp() + 'C',
humidity: sensor.getHumidity() + '%'
});
}, interval);
console.log('Climate control started!');
}
function stopClimateMonitoring() {
clearInterval(sensorReadingInterval);
console.log('Climate control stopped!');
}
return {
start: startClimateMonitoring,
stop: stopClimateMonitoring
};
}
I am watching a button for changes of state like this:
button.watch(function(err, value) {
led.writeSync(value);
if (value == 1) {
monitorClimate().start(1000);
} else {
monitorClimate().stop();
}
});
The problem is that even after the monitorClimate().stop()
call, setInterval keeps getting triggered, thus SocketIO keeps on emitting the sensorReading event.
What am I doing wrong here?
Upvotes: 1
Views: 72
Reputation: 5935
Every time you call monitorClimate()
you are creating a new set of functions so monitorClimate().start()
and monitorClimate().stop()
are not working on the same interval. Try something like:
var monitor = monitorClimate();
button.watch(function(err, value) {
led.writeSync(value);
if (value == 1) {
monitor.start(1000);
} else {
monitor.stop();
}
});
Upvotes: 3