简体   繁体   中英

How to detect user inactivity with JavaScript?

I am trying to have a wordpress page that logs you out with no activity after a certain interval of time. Right now I am just testing the "detect inactivity and do something" part of this (the key part). I found some code on here that partially works; here is the code:

<script>
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 10000);
}
</script>

It is set right now to send that alert every 10 seconds just so I can see immediately it is working (will be much longer later). Anyway; when i run this on a page it does nothing. I can sit there for 5 minutes and nothing happens. But if I leave that tab in my browser, it immediately starts working and sends the alert every 10 seconds if no activity like it is supposed to.

But the whole function does not work if I just sit there on that page and do nothing. Can anyone help with this? Thanks...

Try this instead:

function onInactive(ms, cb){

    var wait = setTimeout(cb, ms); 
    document.onmousemove = document.mousedown = document.mouseup = document.onkeydown = document.onkeyup = document.focus = function(){
        clearTimeout(wait);
        wait = setTimeout(cb, ms);
    };
}

JSFiddle:

http://jsfiddle.net/acNfy/4

You will have to hover your move on the lower right window and stay inactive for 5 seconds to see the results :)

I would try firing the timeout on window load too.

apologies, for the incomplete answer before. A recursive setTimeout might be what you are looking for.

(function interaction(){
    setTimeout(function(){
    // check for movement,
    if(movement...) {
        // if movement do nothing
        }
    else {
        interaction();



    },10000);

})();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM