setInterval不会被清除,函数会一直执行

我有以下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 }; } 

我正在看一个像这样的状态变化的button:

 button.watch(function(err, value) { led.writeSync(value); if (value == 1) { monitorClimate().start(1000); } else { monitorClimate().stop(); } }); 

问题是,即使在monitorClimate().stop()调用之后,setInterval也不断被触发,因此SocketIO一直在发射sensorReading事件。

我在这里做错了什么?

每次调用monitorClimate()都会创build一组新的函数,因此monitorClimate().start()monitorClimate().stop() monitorClimate().start()在相同的时间间隔内不起作用。 尝试像这样:

 var monitor = monitorClimate(); button.watch(function(err, value) { led.writeSync(value); if (value == 1) { monitor.start(1000); } else { monitor.stop(); } });