1

我在空闲库中有这个功能,但我需要以秒为单位计算动作时间,我的意思是活动时间(onclick,onscroll 和 keypress)。

功能是:

    (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 秒,如果页面上没有任何动作,所以我会被重定向到 SessionExpired.aspx。如果有动作,那么每秒都在做++couter。

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

谢谢你。

4

3 回答 3

1

您可以重置计时器

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)
};
于 2016-02-28T09:30:03.783 回答
0

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

您应该在事件之外启动一个间隔线程。

尝试这个:

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);
于 2016-02-28T09:46:15.547 回答
0

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

    <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>
于 2016-02-28T10:33:13.987 回答