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

var mqtt    = require('mqtt');
var client  = mqtt.connect("mqtt://broker.emqx.io:1883",{clientId:"mqtt_AYA"});

var arr = [1,2,3,4];
var options={
    retain:true,
    qos:1};
    
client.on("connect",function(){ 
    console.log("connected  "+ client.connected);
    })

arr.forEach(no => {
    client.on('message',function(topic, message, packet){
        console.log("message is "+ JSON.parse(message));
        // console.log("topic is "+ topic);
    });
    
    setInterval(function(){client.publish('/topic', JSON.stringify(no), options)},5000);

    client.subscribe('/topic', {qos:1});

});

Result –

connected  true
message is 1
message is 1
message is 1
message is 1
message is 2
message is 2
message is 2
message is 2
message is 3
message is 3
message is 3
message is 3
message is 4
message is 4
message is 4
message is 4
[5 secs interval]
Repetition of above 

But I need –

connected  true
message is 1
[5 secs interval]
message is 2
[5 secs interval]
message is 3
[5 secs interval]
message is 4
[5 secs interval]
and end the client

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