Node-red flow -set timeout with js

[{"id":"175bb614.8e64ea","type":"tab","label":"Flow 1","disabled":false,"info":""},{"id":"2c065ea1.db69e2","type":"function","z":"175bb614.8e64ea","name":"","func":"let counter = 0;\n\nfor (let i = 1; i < 11; i++) {\n    \n    setTimeout(dimmer, 2000);\n}\n\nfunction dimmer(){\n    counter = counter + 10;\n    node.send({payload:counter});\n}\n\n","outputs":1,"noerr":0,"initialize":"","finalize":"","x":300,"y":180,"wires":[["864022f5.090eb"]]},{"id":"864022f5.090eb","type":"debug","z":"175bb614.8e64ea","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":470,"y":180,"wires":[]},{"id":"8d92f9e8.dd5718","type":"inject","z":"175bb614.8e64ea","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"","payloadType":"date","x":150,"y":180,"wires":[["2c065ea1.db69e2"]]}]

why does node.send not send a message every 3 sec but always all 10 messages at once at the end?

You setup the timeouts like this:

for (let i = 1; i < 11; i++) {
    setTimeout(dimmer, 2000);

That means you set up 10 timeouts that all run 2 seconds from the moment that for loop is run - in other words, all 10 timeouts occur at the same time (give or take a few microseconds).

If you want to send 10 messages with 2 seconds between each one, you could do:

for (let i = 1; i < 11; i++) {
    setTimeout(dimmer, 2000 * i);

That code sets up the first timeout in 2 seconds, the next timeout in 4 seconds, then 6 seconds and so on.

A bit of further clarification, the setTimeout(dimmer, 2000) call starts the timer and then returns immediately so the loop starts its next iteration straight away, it does not wait for the timer to run down before returning. Then two seconds later dimmer will be called.

with the help of Johannes (JGKK) I managed to use an enocean rocker 4 switch as a dimmer.
He did a perfect job!
Please have a look at this threat:

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