Hello all.
This is my first post over here.
I had to write a simple simulation routine, which takes data from payload once, then spool the loop to generate a series of result values.
After each iteration of that loop the node sends partial results using node.send() method.
The loop is time-based: let's each iteration starts after a second.
How should I write such code to:
- be able to set up time period between iterations?
- be able to break the loop by sending 'stop' in input payload
- be efficient: not block whole NR (I suppose active waiting could do that)
So far I did use the method shown in code below. Everything works but stopping the loop. Simply sending another payload to the input doesn't affect previously running loop at all.
AFAK it runs the new instance of the whole code ( which is proven by sending two data payloads - it starts two separate simulations)
Is it possible to achieve that?
Thanks in advance
var c = 0;
var t;
var timer_is_on = 0;
var steps = 320; //48*2;
var inc = 4; // mins
var ts = new Date(msg.payload.ts);
ts.setUTCHours(0,0,0,0);
if (msg.payload == 'stop') {
stopCount();
node.done();
}
function simulate() {
msg.payload.ts = ts.getTime();
ts.setUTCMinutes(ts.getUTCMinutes()+inc);
node.send(msg);
}
function timedCount() {
simulate(c);
c = c + 1;
t = setTimeout(timedCount, 500);
if (c>=steps) {
stopCount();
}
}
function startCount() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
node.error('stop');
clearTimeout(t);
timer_is_on = 0;
}
startCount();