鼠标移动/单击或按键时刷新倒数计时器

时间:2017-09-07 09:02:02

标签: javascript jquery timer

如果没有采取任何行动,我会使用倒数计时器来销毁我的会话。

  var idleTime = 0;
  function Timer(duration, display)  {
    var timer = duration, hours, minutes, seconds;
    setInterval(function () {
        hours = parseInt((timer /3600)%24, 10)
        minutes = parseInt((timer / 60)%60, 10)
        seconds = parseInt(timer % 60, 10);

        hours = hours < 10 ? "0" + hours : hours;
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;

        display.text(hours +":"+minutes + ":" + seconds);
        if(hours == 0 && minutes == 0 && seconds == 0){
            $.ajax({
              url:'../ajax/logoutuser.php?action=logout',

              success: function(data){
                window.location.href = '../index.php';
              }
            });
        }else{
           --timer;
        }

    }, 1000);
}

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 1) { // 20 minutes
         var twentyFourHours = 1 * 60 * 60;
        var display = $('#time');
        Timer(twentyFourHours, display);
    }
}

$(document).ready(function(){
   var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $(this).mousemove(function (e) {
        idleTime = 0;
    });
    $(this).keypress(function (e) {
        idleTime = 0;
    });

});

它首先起作用,但问题是当倒数计时器开始运行时,即使我从我的页面做出任何动作,如鼠标点击/鼠标移动/按键,它也不刷新倒计时器..我想要什么如果我倒计时器运行,如果我做另一个动作倒数计时器将重新加载。

就像当我刷新我的页面时,倒计时器也会刷新..有没有办法可以做到?。

1 个答案:

答案 0 :(得分:0)

如果您想重置setInterval,那么SO已经有了答案: https://stackoverflow.com/a/8126515/6053654