2017-02-21 58 views
0

我想在用戶空閒超時5秒時顯示優惠橫幅,但下面的代碼顯示優惠橫幅每空閒5秒。但是我想只對第一個空閒執行以下功能一次5 seconds.Any身體幫我出只對用戶空閒超時執行一次功能

$(document).ready(function(){ 

      idleTime = 0;   


      //Increment the idle time counter every five second. 
      var idleInterval = setInterval(timerIncrement, 5000); 

      function timerIncrement() 
      { 
      console.log(idleTime++); 
      if (idleTime > 5) 
      { 
       doPreload();  

      } 
      } 

      //Zero the idle timer on mouse movement. 
      $(this).mousemove(function(e){ 

       idleTime = 0; 

      }); 

      function doPreload() 
      { 
      $('#add-click').click(); 

      } 

     }); 
+0

移動的,如果(空閒...)裏面的doPreload ..我認爲你不能檢查計時器內的idleTime變量,因爲封閉。 – Max

回答

1

你需要使用setTimeout代替setInterval

window.setTimeout(function(){ 
     timerIncrement(); 
}, 5000); 

這將只執行一次。

+0

即使它不工作 – Nageswar

+0

你可以創建一個JSFiddle或plunkr,以便我可以檢查。 –

+0

等待我將添加並讓你知道 – Nageswar

0

爲什麼不嘗試setTimeout而不是setInterval?

+0

這應該是一個評論而不是答案。 –

+0

我不能評論,需要50個代表:) – Sooraz

0

您只使用鼠標,如果什麼用戶使用鍵盤的工作,你有這個功能檢查也

var inactivityTime = function() { 
var temp; 
window.onload = resetTimer; 
document.onmousemove = resetTimer; 
document.onkeypress = resetTimer; 

function resetTimer() { 
    clearTimeout(temp); 
    temp = setTimeout(logout, 3000) 
    // 1000 milisec = 1 sec 
} 
}; 
0

正確的邏輯移動:

var idleInterval = setInterval(timerIncrement, 1000); 
    function timerIncrement() { 
    console.log(idleTime++); 
    if (idleTime == 5) { 
     doPreload(); 
     idleTime = 0; // reset idleTime variable  
     } 
    } 

    /** This will increase counter by one every second, 
    * and if counter reaches to 5 then call to banner 
    * display and reset counter. 
    */