2

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...

Mulan
  • 119,326
  • 28
  • 214
  • 246
mifalcon
  • 43
  • 1
  • 8
  • When you just type that into your console, but don't do anything, of course nothing will happen. The timer will be initialised by the *first* mousemove that you make… – Bergi Jul 12 '14 at 20:27

2 Answers2

10

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

imbondbaby
  • 6,253
  • 3
  • 18
  • 53
  • 2
    The accepted answer has the liability that any existing event handlers on those events will be overwritten. There are several excellent and safer answers to the problem here: http://stackoverflow.com/questions/667555/ – grahamesd May 26 '15 at 19:23
  • Thanks! @imbondbaby – DanyMartinez_ May 04 '21 at 21:46
-2

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);

})();
Motti Horesh
  • 800
  • 8
  • 10
  • Hello Motti: thanks for your response; but I am really unsure what you mean, can you clarify it any or provide any more info? Thanks…. – mifalcon Jun 21 '14 at 05:27