2015-06-13 78 views
1

我有以下功能:的setInterval没有得到清除,功能不断得到执行

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

如果通过每次使用API​​调用函数来重新创建范围,那么关闭的目的是什么?您的不同通话不会在同一地点执行。这是不同的功能,所以不同的时间间隔。 –

+0

你需要一个执行者服务,代码是混乱的。 –

+0

谢谢你们!我显然是一个新手,所以找到最好的模式往往是我的挑战。 @RomanC你能指点我一些Executor服务上的阅读材料吗?或者,也许一些源代码实现它...简单的谷歌搜索导致我一个NPM包。这是你指的是什么? –

回答

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

非常感谢@wezzy!我把'sensorReadingInterval'移到了'global'范围,随着你的添加(抓取函数的一个实例),它使它工作。我会试着想一个更好的模式。从这个问题的评论来看,这可能不是正确的做法。 –

+0

我很高兴,这有助于你:-) – wezzy

+1

这个答案不能解决任何问题。每次按下按钮时,您仍然调用'monitorClimate'并创建新的'start' /'stop'功能。对全局'sensorReadingInterval'的更改自行解决了问题。 –