Hi,
I am running into an issue with a function i thought was rather simple. But it drives me mad
I am trying to change the state of a lamp, and that works fine until I add a delay node.
This is my function (simplified):
if (msg.payload === "start1")
{
var brightness = 0;
for (var i=1; i<255; i++) // brightness 254 = 100%
{
brightness = brightness+1;
msg.payload = { "brightness": + brightness }
node.send(msg);
}
}
As said, this works fine, but it pushes out all 254 messages in sequence. And I want some delay between the messages. So I added a rate limit node, 1 message every second. But what happens is that the first message contains a 1, and all 253 messages following the first conatins 254.
I don't get it, why?
How can I get it to send a message per second? I tried a delay loop within the function, but that didn't work at all.
Thanks for your help.
node.js passes variables by reference so when you re-use msg.payload you are just passing out the reference to that. so the loop iterates (really fast) and updates the same variable location to all the values ending at 254.... which by the time the delay sends that variable is now 254 from then on.
What you need to do is to either clone the msg using RED.util.cloneMessage( ) - or create a new msg object.
Generally we advise users to try to maintain the existing msg object if possible (so all the other properties are still there) - but if you just need the payload further along the flow then it's probably easier to just create a new payload so instead of the last two lines of your function - maybe just use
node.send({payload:{ "brightness": brightness } });
1 Like
Wow! Thank you for the quick response.
It works like a charm now. I still don't understand the cloning part of your answer but I will dive in the documentation for that.
thanks again!