How to detect idle time in JavaScript elegantly?

2018-12-31 02:26发布

Is it possible to detect "idle" time in JavaScript?
My primary use case probably would be to pre-fetch or preload content.

Idle time: Period of user inactivity or without any CPU usage

标签: javascript
30条回答
爱死公子算了
2楼-- · 2018-12-31 03:22

You could probably detect inactivity on your web page using the mousemove tricks listed, but that won't tell you that the user isn't on another page in another window or tab, or that the user is in Word or Photoshop, or WOW and just isn't looking at your page at this time. Generally I'd just do the prefetch and rely on the client's multi-tasking. If you really need this functionality you do something with an activex control in windows, but it's ugly at best.

查看更多
步步皆殇っ
3楼-- · 2018-12-31 03:22

Tried @freddoo solution but it didn't work for 1 minute timeouts so I've changed it slightly to record the date+time when the user last clicked on the page and in my timerIncrement function I calculate the difference between the current time and the last clicked time and if the value happens to be bigger or equal to the timeout value then I redirect:

var clickedDate = new Date();
var idleTime = 1;//

function timerIncrement() {

    var nowDate = new Date();
    var diffMs = (nowDate - clickedDate); //Milliseconds between now & the last time a user clicked somewhere on the page
    var diffMins = Math.round(((diffMs % 86400000) % 3600000) / 60000); //Convert ms to minutes

    if (diffMins >= idleTime) {
        //Redirect user to home page etc...
    }
}

$(document).ready(function () {

    var idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    $(this).click(function (e) {
        clickedDate = new Date();
    });

});
查看更多
浅入江南
4楼-- · 2018-12-31 03:23

I know it a relatively old question, but I had the same issue and I found a quite good solution.

I used: jquery.idle and I only needed to do:

$(document).idle({
  onIdle: function(){
    alert('You did nothing for 5 seconds');
  },
  idle: 5000
})

See JsFiddle demo.

(Just for Info: see this for back-end event tracking Leads browserload)

查看更多
明月照影归
5楼-- · 2018-12-31 03:23

The problem with all these solutions, although correct, they are impractical, when taking into account the session timeout valuable set, using PHP, .NET or in the Application.cfc file for Coldfusion developers. The time set by the above solution needs to sync with the server side session timeout. If the two do not sync, you can run into problems that will just frustrate and confuse your users. For example, the server side session timeout might be set to 60 minutes, but the user may believe that he/she is safe, because the JavaScript idle time capture has increased the total amount of time a user can spend on a single page. The user may have spent time filling in a long form, and then goes to submit it. The session timeout might kick in before the form submission is processed. I tend to just give my users 180 minutes, and then use JavaScript to automatically log the user out. Essentially, using some of the code above, to create a simple timer, but without the capturing mouse event part. In this way my client side & server side time syncs perfectly. There is no confusion, if you show the time to the user in your UI, as it reduces. Each time a new page is accessed in the CMS, the server side session & JavaScript timer are reset. Simple & elegant. If a user stays on a single page for more than 180 minutes, I figure there is something wrong with the page, in the first place.

查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 03:23

Here is the best solution I have found: http://css-tricks.com/snippets/jquery/fire-event-when-user-is-idle/

Here is the JS:

idleTimer = null;
idleState = false;
idleWait = 2000;

(function ($) {

    $(document).ready(function () {

        $('*').bind('mousemove keydown scroll', function () {

            clearTimeout(idleTimer);

            if (idleState == true) { 

                // Reactivated event
                $("body").append("<p>Welcome Back.</p>");            
            }

            idleState = false;

            idleTimer = setTimeout(function () { 

                // Idle Event
                $("body").append("<p>You've been idle for " + idleWait/1000 + " seconds.</p>");

                idleState = true; }, idleWait);
        });

        $("body").trigger("mousemove");

    });
}) (jQuery)
查看更多
呛了眼睛熬了心
7楼-- · 2018-12-31 03:24

You can use the below mentioned solution

var idleTime;
$(document).ready(function () {
         reloadPage();
        $('html').bind('mousemove click mouseup mousedown keydown keypress keyup submit change mouseenter scroll resize dblclick', function () {
            clearTimeout(idleTime);
            reloadPage();
        });
});
function reloadPage() {
    clearTimeout(idleTime);
    idleTime = setTimeout(function () {
        location.reload();
    }, 3000);
}
查看更多
登录 后发表回答