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:15

(Partially inspired by the good core logic of Equiman earlier in this thread.)

sessionExpiration.js


sessionExpiration.js is lightweight yet effective and customizable. Once implemented, use in just one row:

sessionExpiration(idleMinutes, warningMinutes, logoutUrl);
  • Affects all tabs of the browser, not just one.
  • Written in pure JavaScript, with no dependencies. Fully client side.
  • (If so wanted.) Has warning banner and countdown clock, that is cancelled by user interaction.
  • Simply include the sessionExpiration.js, and call the function, with arguments [1] number of idle minutes (across all tabs) until user is logged out, [2] number of idle minutes until warning and countdown is displayed, and [3] logout url.
  • Put the CSS in your stylesheet. Customize it if you like. (Or skip and delete banner if you don't want it.)
  • If you do want the warning banner however, then you must put an empty div with ID sessExpirDiv on your page (a suggestion is putting it in the footer).
  • Now the user will be logged out automatically if all tabs have been inactive for the given duration.

This is an example of what it looks like in action, if you don't change the CSS.

demo_image

查看更多
旧人旧事旧时光
3楼-- · 2018-12-31 03:17
<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every minute.
    idleInterval = setInterval(timerIncrement, 60000); // 1 minute

    //Zero the idle timer on mouse movement.
    $('body').mousemove(function (e) {
     //alert("mouse moved" + idleTime);
     idleTime = 0;
    });

    $('body').keypress(function (e) {
      //alert("keypressed"  + idleTime);
        idleTime = 0;
    });



    $('body').click(function() {
      //alert("mouse moved" + idleTime);
       idleTime = 0;
    });

});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 10) { // 10 minutes

        window.location.assign("http://www.google.com");
    }
}
</script> 

I think this jquery code is perfect one , though copied and modified from above answers!! donot forgot to include jquery library in your file!

查看更多
闭嘴吧你
4楼-- · 2018-12-31 03:19

Without using jQuery, only JavaScript:

var inactivityTime = function () {
    var t;
    window.onload = resetTimer;
    // DOM Events
    document.onmousemove = resetTimer;
    document.onkeypress = resetTimer;

    function logout() {
        alert("You are now logged out.")
        //location.href = 'logout.php'
    }

    function resetTimer() {
        clearTimeout(t);
        t = setTimeout(logout, 3000)
        // 1000 milisec = 1 sec
    }
};

Credits: http://forums.devshed.com/javascript-development-115/alert-time-inactivity-click-logout-501444.html

You can add more DOM events if you need to. Most used are:

document.onload = resetTimer;
document.onmousemove = resetTimer;
document.onmousedown = resetTimer; // touchscreen presses
document.ontouchstart = resetTimer;
document.onclick = resetTimer;     // touchpad clicks
document.onscroll = resetTimer;    // scrolling with arrow keys
document.onkeypress = resetTimer;

DOM Events list: http://www.w3schools.com/jsref/dom_obj_event.asp

Remember use window, or document according your needs. Here you can see the differences between them: What is the difference between window, screen, and document in Javascript?

查看更多
何处买醉
5楼-- · 2018-12-31 03:19

I have created a small lib that does this a year ago:

https://github.com/shawnmclean/Idle.js

Description:

Tiny javascript library to report activity of user in the browser (away, idle, not looking at webpage, in a different tab, etc). that is independent of any other javascript libraries such as jquery.

Visual Studio users can get it from NuGet by: PM> Install-Package Idle.js

查看更多
孤独总比滥情好
6楼-- · 2018-12-31 03:21

Here is a simple script using JQuery that handles mousemove and keypress events. If the time expires, the page reload.

<script type="text/javascript">
var idleTime = 0;
$(document).ready(function () {
    //Increment the idle time counter every minute.
    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;
    });
});

function timerIncrement() {
    idleTime = idleTime + 1;
    if (idleTime > 19) { // 20 minutes
        window.location.reload();
    }
}
</script>   
查看更多
皆成旧梦
7楼-- · 2018-12-31 03:21

All the previous answers have an always-active mousemove handler. If the handler is jQuery, the additional processing jQuery performs can add up. Especially if the user is using a gaming mouse, as many as 500 events per second can occur.

This solution avoids handling every mousemove event. This result in a small timing error, but which you can adjust to your need.

function setIdleTimeout(millis, onIdle, onUnidle) {
    var timeout = 0;
    $(startTimer);

    function startTimer() {
        timeout = setTimeout(onExpires, millis);
        $(document).on("mousemove keypress", onActivity);
    }

    function onExpires() {
        timeout = 0;
        onIdle();
    }

    function onActivity() {
        if (timeout) clearTimeout(timeout);
        else onUnidle();
        //since the mouse is moving, we turn off our event hooks for 1 second
        $(document).off("mousemove keypress", onActivity);
        setTimeout(startTimer, 1000);
    }
}

http://jsfiddle.net/q8wLuLbw/

查看更多
登录 后发表回答