Loops inside a node

I am delving into loops for some reason.

I send a payload (number) and the node spits out that many messages.
(Contents not important)

So for now this is the code:

let x = msg.payload;
let y = 0;
context.set("COUNT",x);   //  Not really needed?

while (y < x)
    y = y + 1;
//    node.send(y);    //  Not sure on structure.   But.....

But when I inject a value, I get this as an error:

TypeError: Cannot read property 'startsWith' of undefined

I've seen this before, but can't remember where and why.

Putting that aside, what am I missing on the loop?

Thanks in advance.


Ok, found first problem in line:


Originally I put a . rather than a ,.

But now the delay isn't happy.

How do I delay?

Delay as such is not available in javascript. You have to use setTimeout in some way. You could eventually write a function with the name 'delay' but inside, you have to use setTimeout

Yeah, I was searching and found setTimeout but the docs on it are above my skill set to read and understand. :frowning:

let x = msg.payload;
let y = 0;

function f(x,y) {
    y += 1;
    if(y < x){
        setTimeout( f, 1000, x, y );


1 Like


I still need to learn more. This saved me a lot of mucking about.

Good to hear, I anyway had that code in front of me recently, I then needed a similar delay feature as well :wink:

You might be better to split the loop out into a number of nodes and use a Delay node to do the delay.

I do agree @Colin. Alas I was wanting to just optimise the screen size.

Though of course: I could use a sub flow node.

It is only for a very small specific use and it is just in testing phase for now.
I may not use/need it anyway.

It just seems what @krambriw showed me is possibly the Goldilocks code.

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.