计数器在几秒钟内空闲 jquery



我在空闲库中有这个函数,但我需要的是计算以秒为单位的操作时间,我的意思是活动时间(点击、滚动和按键)。

功能是:

    (function () { 
var minutes = false;
var interval = 1000; 
var IDLE_TIMEOUT = 5; 
var idleCounter = 0;
var counter=0;
document.onclick = document.onkeypress = function () {
    idleCounter = 0;
    setInterval(function () {
++counter;; 
 }, 1000);
};
window.setInterval(function () {
    if (++idleCounter >= IDLE_TIMEOUT) {
    alert(counter);
        document.location.href = "SessionExpired.aspx";
    }
}, interval);
}());

如果页面上没有操作,此函数将等待 5 秒,因此我将被重定向到 SessionExpire.aspx.如果有操作,那么我每秒都在做 ++couter 。

我需要这个计数器在几秒钟内。

谢谢。

您可以重置计时器

var counter;
var counterSeconds;
document.onclick = document.onkeypress = function () {
    idleCounter = 0; // Set counter to 0 on each keypress/page click
    clearInterval(counter) // Every time they click, clear the old interval and start a new one below
    counter = setInterval(function () { // assign the interval to a variable so we can clear it
       if (idleCounter > IDLE_TIMEOUT) { // Check if they've idled too long
            document.location.href = "SessionExpired.aspx"; // Redirect them if they have
       } 
       ++counterSeconds;
       ++idleCounter; // Should increment 1/sec depending on your computer.
    }, 1000); // Ticks at 1000 milliseconds (1 Second)
};

这里的一个问题是,每次单击或按键事件都会启动新的间隔函数,这会导致多个线程更新相同的变量。

您应该在事件外部启动间隔线程。

试试这个:

document.onclick = document.onkeypress = function () {
    idleCounter = 0;
};
var activeTimer = setInterval(function () {
   ++counter; 
}, interval);
var idleTimer = window.setInterval(function () {
    if (++idleCounter >= IDLE_TIMEOUT) {
        alert(counter);
        document.location.href = "SessionExpired.aspx";
    }
}, interval);

这正是我想要的,我做到了:

    <script  src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" ></script>
      <script src="./e-lawyer/JS/idle.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>timertest</title>
    <script language="javascript">
    var it;
    x = 0;
    $(document).ready(function(){
        $('.status').html('active');
    });

    function count() { 
    x+=1;
    $('.usercount').html(x);
    }
    (function() {
var timeout = 2000;
$(document).bind("idle.idleTimer", function() {
clearInterval(it);    
    $('.status').html('idle');
});

$(document).bind("active.idleTimer", function() {
  it = setInterval(count, 1000);
 $('.status').html('active');
});
       $.idleTimer(timeout);
    })(jQuery);
    </script>
    </head>
    <body>
    <div class="status" style="border:1px dashed black; width:500px; height:50px;"></div>
    <div class="usercount"style="border:1px dashed black; width:500px; height:50px;"></div>
    </body>
    </html>

相关内容

  • 没有找到相关文章

最新更新