0

I want to run calculateSomething function for a specific period of time, for example for 1 minute which this function receive messages from MQTT protocol. After 1 minute, this function will sleep or stop receiving data from MQTT for 1 minute, then start to run again.

client.on('message', function (topic, message) {
    calculateSomething(topic, message);
})


function calculateSomething(top, param) { 
    let graph = new Graph();
    if(top === 'togenesis') {
        graph.addEdgetogenesis(param.toString())

    } else if (top === 'DAG'){
        graph.addEdge(param.toString())  
    }
} 

I have tried setInterval() but it keep run the function repeatly but I don't want to repeat the function because it is in real time. I also have tried setTimeout() but this only delay for the first time.

Any ideas please how could solve it? thanks in advance.

hardillb
  • 54,545
  • 11
  • 67
  • 105
ismsm
  • 143
  • 2
  • 11
  • What do you want to do with inbound messages in the minute when you're sleeping? Just ignore them? Queue them for processing later? – jfriend00 Jan 16 '21 at 23:07
  • @jfriend00 Yes, I want the algorithm do other things in this 1 minute and in the mean time the data is queued to be processed later. – ismsm Jan 17 '21 at 09:47
  • Well, the answer you accepted does not queue the data to be processed later, it just ignores any data that arrives during the 1 minute period of rest. – jfriend00 Jan 17 '21 at 09:55
  • could you help me how to do that? any hints please ? – ismsm Jan 17 '21 at 10:05
  • What is the real purpose of the 1 minute pause in processing? I feel like I need to know what you're really trying to accomplish to know what implementation to best suggest. – jfriend00 Jan 17 '21 at 10:11

1 Answers1

2

Try this, the execution of your function is subordinated by a boolean variable that I have named start which serves to keep the function operational (start = true) or not (start = false). The setInterval cycles for one minute and alternates the state of the boolean variable start.

client.on('message', function (topic, message) {
    calculateSomething(topic, message);
})

var start = true;

setInterval(function(){
    if(start){
        start = false;
    } else {
        start = true;
    }
}, 60000); //1 minute

function calculateSomething(top, param) { 
    if(start){ //the function is executed only if start is true
        let graph = new Graph();
        if(top === 'togenesis') {
            graph.addEdgetogenesis(param.toString())

        } else if (top === 'DAG'){
            graph.addEdge(param.toString())  
        }
    }
} 
Blackjack
  • 1,322
  • 1
  • 16
  • 21