setInterval 没有被清除,函数一直在执行

setInterval doesn't get cleared, function keeps getting executed

我有以下功能:

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();
    }
});