我有以下功能:
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事件。我在这里做错了什么?
最佳答案
每次调用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();
}
});
关于javascript - setInterval不清除,函数不断执行,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30822866/