Skip to content
Advertisement

Mqtt publish each element of an array using nodejs

I have a Mqtt client. I need it to publish each element with 5 seconds interval and receive each in on_message callback. But my code publishes each element with same no of times as array length.

Example –

My code

JavaScript

Result –

JavaScript

But I need –

JavaScript

Advertisement

Answer

Your set Interval and subscribe are in the forEach loop. This means you are starting 4 intervals at the same time. Since every value subscribes to every message, you get 4 subscribers. When all setIntervals publish the message at the same time all 4 subscribers show the message. Therefore getting the result you see.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement