Updated version of Node-RED Loop
Hickmat 100000QA3T Comment (1) Visits (7515)
So following my experiments with my Christmas lights I'd come to the conclusion that I really needed to be less "hacky" and update my looping approach to remove the dependency on global variables. As I had a few mins this evening I set about fixing this in a test flow.
The approach I wanted to move to was to use the msg structure to hold the control semaphore rather than rely on the global context. In this way I can have multiple instances of a loop running with out impacting each other. I have a question I need to ask the NodeRED guys at some point re how the flows work, I'm assuming a I could have multiple message instances being processed in parallel in a flow which would really hit an issue with the way I was using the global context. Anyway how ever it works I really don't like using globals if I can avoid it
The refactored code uses msg.loop to hold the on / off value to control the execution of the loop. To test this I created two instances of the loop code triggered from the a common inject node. One loop is controlled by a global context variable but is used to switch the msg.loop value. The other loop was set to keep msg.loop set to 'on' so the loop should keep going. Based on this the flow is as follows:
and the code for the flow is: