Node Red setInterval causing stale readings on redeploy
<p>I'm tinkering around with Node-Red and have made a my first simple custom node which adds to a counter each time an input is received.</p>

<p>The node also contains a call to <code>setInterval</code> which after ever 5 seconds calls <code>node.send()</code> with the counter value in the <code>msg.payload</code>.</p>

<pre><code>module.exports = function(RED) {
  function MyNode(config) {

    RED.nodes.createNode(this, config);
    var node = this;
    var count = 0;

    this.on('input', function(msg) {
        count++;
    });    

    setInterval(function() {

        var msg = 
        { 
            payload: { countTotal : count }
        };
        node.send(msg);
        return;

    }, 5000); // 5 Second Timer

  }
  RED.nodes.registerType("my-node", MyNode);
}
</code></pre>

<p>If I deploy the flow the node is behaving as expected.  However if I redeploy the flow I seem to be receiving two calls from the node.send().  </p>

<p>One which is the correct value and the other is the last/stale value that was current before the redeploy.</p>

<p>For example:</p>

<p><strong>Deploy and click input 6 times before 5 seconds</strong></p>

<p>05 seconds: countTotal = 6</p>

<p>10 seconds: countTotal = 6</p>

<p>15 seconds: countTotal = 6</p>

<p><strong>Re-deploy and click input 3 times before 5 seconds</strong></p>

<p>05 seconds: countTotal = 3</p>

<p>05 seconds: countTotal = 6 [Old Stale reading]</p>

<p>If I restart node-red then it starts behaving as I'd expect.</p>

<p><strong>My questions</strong></p>

<p>Is this the correct approach to having a timer within a node, if not what should I be doing? If yes, why is the stale data coming through?</p>

<p>Many thanks.</p>

<p><strong>UPDATE</strong></p>

<p>Off the back off the answer from knolleary I've tried the following change</p>

<pre><code>module.exports = function(RED) {
  function MyNode(config) {

    RED.nodes.createNode(this, config);
    var node = this;
    var count = 0;

    var timer = setInterval(function() {    

        var msg = { payload: { countTotal : count }};
        node.send(msg);
        return;

    }, 5000); // 5 Second Timer

    this.on('input', function(msg) {
        count++;
    });  

    this.on('close', function(msg) {
        clearTimeout(timer);    
    });     

  }
  RED.nodes.registerType("my-node", MyNode);
}
</code></pre>

<p>...however now when a the flow is re-deployed, it completely stops!!</p>