如何运行 function for specific time and sleep for a specific time?

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

我想 运行 calculateSomething 函数在特定时间段内运行,例如 1 minute,此函数接收来自 MQTT 协议的消息。 1 分钟后,此函数将休眠或停止从 MQTT 接收数据 1 minute,然后再次开始 运行。

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

我试过 setInterval() 但它会重复 运行 函数,但我不想重复该函数,因为它是实时的。我也试过 setTimeout() 但这只是第一次延迟。

有什么办法可以解决吗?提前致谢。

试试这个,函数的执行受我命名为 start 的布尔变量的影响,它用于保持函数运行(开始 = 真)或不运行(开始 = 假)。 setInterval 循环一分钟并交替布尔变量 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())  
        }
    }
}