2017-02-21 53 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. 
    */