ismsm
ismsm

Reputation: 173

How to run function for specific time and sleep for a specific time?

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.

Upvotes: 0

Views: 94

Answers (1)

Blackjack
Blackjack

Reputation: 1112

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())  
        }
    }
} 

Upvotes: 1

Related Questions