我有以下功能:
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
};
}
我正在观看状态变化的按钮:
button.watch(function(err, value) {
led.writeSync(value);
if (value == 1) {
monitorClimate().start(1000);
} else {
monitorClimate().stop();
}
});
问题是即使在monitorClimate().stop()
调用之后,setInterval仍然会被触发,因此SocketIO继续发出sensorReading事件。
我在这里做错了什么?
答案 0 :(得分:3)
每次拨打monitorClimate()
时,您都会创建一组新功能,因此monitorClimate().start()
和monitorClimate().stop()
的工作时间不同。尝试类似:
var monitor = monitorClimate();
button.watch(function(err, value) {
led.writeSync(value);
if (value == 1) {
monitor.start(1000);
} else {
monitor.stop();
}
});