2017-01-14 2 views
0

ノードjsで60秒間だけコードブロックを実行する必要があります。nodejsでn秒間コードブロックを実行

function someFunc() 
{ 
    console.log("hello"); 
    //event occurs - so time should increase by 5 secs. 
} 

特定のイベントでは、時間がさらに5秒増加するはずです。これをどのように達成するのですか? setTimeoutは、60秒後に実行を開始してから機能しません。

+2

可能な複製(http://stackoverflow.com/questions/27030920/run-a-function-for-a-specific -時間の長さ) – code11

答えて

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>

関連する問題