我需要在节点js中运行一段代码仅60秒。
function someFunc()
{
console.log("hello");
//event occurs - so time should increase by 5 secs.
}
在特定事件中,时间应进一步增加5秒。我该如何实现这一目标?
setTimeout
因为它在60秒后开始运行而无效。
答案 0 :(得分:0)
可能不是最好的解决方案,但几乎更接近您的要求。评论将解释代码。
单击按钮再增加5秒。刚刚使用按钮进行活动。您可以将其替换为自定义事件。
var timer = 0; //A timer for execution
var initialTime = 5000; //This is your 60 seconds, change this
var func = function(){ //code block to execcute after time
console.log("Hello");
console.log(initialTime); //gives 0 Just to check timeout.
};
var timeOut; //timeOutId
timeOut = setTimeout(func, initialTime); //initial timeOut
setInterval(function(){ //to run timer
document.getElementById("timer").innerHTML = ++timer;
initialTime -= 1000; //reducing time from initially set Time
}, 1000);
function incrementer(){ //event to increase 5 more seconds
clearTimeout(timeOut);
initialTime += 5000; //increasing by 5 seconds
timeOut = setTimeout(func, initialTime); //updated timeOut
}
<button onClick="incrementer()" id="timer"></button>