Thach Huynh
Thach Huynh

Reputation: 1293

Nodejs MQTT: set timeout after receiving message

After the first time receiving message by MQTT, I want to set a timeout for about 1 min. If there is no more message in 1 min, I want to notify something. Are there any way that I can do it ?

client.on('message', function (topic, message) {  
    // if in one minute timeout, there is no more message 
    // console.log("warning")
}

Upvotes: 2

Views: 1342

Answers (1)

Abdul Alim Shakir
Abdul Alim Shakir

Reputation: 1202

Client.on() function will only trigger if a message is received. setInterval() function can be used outside which will continuously run after a second. Now count second and when it becomes a minute, you can notify something. Do not forget to initialize counter when a message is received or when it becomes a minute.

The following code will detect if there is no message received in a minute.

var i = 1
client.on('message', function (topic, message) {
console.log(message.toString())
i=1
})

setInterval(function(){
i++
if(i==60)
{
console.log("No Msg");
i=1;
}
},1000)

Upvotes: 4

Related Questions