2017-08-03 8 views
0

以下のjavascriptコードは、10秒ごとにページを自動更新します。mousemoveのタイマーをリセットしてキーを押す

私の質問は、mousemoveとkeypressのタイマーをリセットする方法です。

のJavaスクリプト

<script type="text/javascript" language="JavaScript"> 

     var secs; 
     var timerID = null; 
     var timerRunning = false; 
     var delay = 1000; 

     function InitializeTimer(seconds) { 
      //length of the timer, in seconds 
      secs = seconds; 
      StopTheClock(); 
      StartTheTimer(); 
     } 

     function StopTheClock() { 
      if (timerRunning) 
       clearTimeout(timerID); 
      timerRunning = false; 
     } 

     function StartTheTimer() { 
      if (secs == 0) { 
       StopTheClock(); 
       window.location.href = window.location.href; 
      } 
      else { 
       document.getElementById("lbltime").innerText = secs + " "; 
       secs = secs - 1; 
       timerRunning = true; 
       timerID = self.setTimeout("StartTheTimer()", delay); 
      } 
     } 
</script> 

事前にありがとうございます。

+0

//上記の例では、結果を割り当てます。 var timeoutHandle = window.setTimeout(...); //クリック機能では、clearTimeoutを呼び出します。 window.clearTimeout(timeoutHandle); // setTimeoutを再度呼び出してタイマーをリセットします。 timeoutHandle = window.setTimeout(...); – anu

答えて

0

私が正しくあなたを理解している場合、このような何か(本当に基本的な例:タイマはのMouseMoveとキー操作でリセットされます):

var elem = document.getElementById("timer"), timeout, startTimer = function timer() { 
 
    elem.textContent++; 
 
    timeout = setTimeout(timer, 1000) 
 
} 
 
function resetTimer() { 
 
    // here you reset the timer... 
 
    clearTimeout(timeout); 
 
    elem.textContent = -1; 
 
    startTimer(); 
 
    //... and also you could start again some other action 
 
} 
 
document.addEventListener("mousemove", resetTimer); 
 
document.addEventListener("keypress", resetTimer); 
 
startTimer();
<span id="timer">-1</span> - Move cursor or press a key to reset timer.

私が推測すると、ページを遅らせたいですページにユーザーのアクティビティがあった場合は再読み込みを行います。 reload()関数では、タイマーの値が制限(60秒など)に達したかどうかをチェックするだけです。はいの場合は、リロードを実行します。しかし、たとえばカーソルの移動を早く開始すると、mousemoveイベントを処理すると、ブラウザのタブのCPU使用率が高くなることに注意してください。いくつかの重要な領域を選択し、対応する要素にハンドラを設定することができます。たとえば、keypressイベントはコメントフォームでのみ聴くことができ、mousemoveはメニューまたは記事でのみ聴くことができます。

PS。また、考慮に入れるthat

キープレスイベントはキーが押下されたときに発生し、そのキーは通常、例えば、ユーザーを押す場合、

のでctrlまたはalt文字値を生成していますイベントは発生しません。

0

あなたのコードは、私の意見ではあまりにも枝分かれしているように見えますが、私はそれを少し単純化しています。

window.refreshTimeout = null; 
 

 
function refreshPage(){ 
 
    location.reload(); 
 
} 
 

 
function refresh(){ 
 
    clearTimeout(window.refreshTiemout); 
 
    window.refreshTimeout = setTimeout(refreshPage, 2000) 
 
} 
 

 
window.refreshTimeout = setTimeout(refreshPage, 2000) 
 
window.addEventListener('mousemove', refresh)
<h4>HelloWorld</h4>

あなたが見ることができるように、あなたが以前のタイムアウトをキャンセルして新しいものを開始し、その中マウス移動(あなたも他の人を添付することができます)のためのウィンドウにイベントリスナーを付けます。当初、あなたはもちろんタイムアウトを開始します。

関連する問題