4

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

1
  • 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… Commented Jul 12, 2014 at 20:27

4 Answers 4

16

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

Sign up to request clarification or add additional context in comments.

3 Comments

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: stackoverflow.com/questions/667555
As @grahamesd said, the answers here are more complete: stackoverflow.com/questions/667555/…
So much helped me! Many thanks!
1

I like to remove the listeners when the inactivity takes place so this is a quick example of how to detect "no interaction":

const IDLE_TIMEOUT = 5000; // in milliseconds
const idle_events = {
    load: false,
    mousemove: false,
    mousedown: false,
    touchstart: false,
    touchmove: false,
    keydown: false,
    click: false,
    scroll: true
}
let time;

function sendIdleEvent() {
    removeListeners()

    // Do something here
    // ...
}

function resetIdleTimeout() {
    clearTimeout(time)
    time = setTimeout(sendIdleEvent, IDLE_TIMEOUT)
}

function addListeners() {
    Object.entries(idle_events).forEach(([event_name, capture]) => {
        window.addEventListener(event_name, resetIdleTimeout, capture)
    })
}

function removeListeners() {

    Object.entries(idle_events).forEach(([event_name, capture]) => {
        window.removeEventListener(event_name, resetIdleTimeout, capture)
    })
}

addListeners()
resetIdleTimeout()

Just change the IDLE_TIMEOUT value with the time you want to consider the user is not interacting and add whatever you need to do inside the sendIdleEvent function.

Adding or removing "listeners" you can define exactly what you consider "no interaction".

Comments

1

ES6 Version Of this answer https://stackoverflow.com/a/24338601/1591819

Class Main{
 
    OnInactive(ms, cb) {

        if(this.ScreenLock){
            console.log('debug', "Screen is already locked, skipping OnInactive setup.");
            return;
        }

        console.log('debug', "Setting up inactivity timeout for " + ms + " milliseconds.");
        if (typeof ms !== 'number' || ms <= 0) {
            console.log('error', "Invalid timeout duration provided: " + ms);
            throw new Error("Timeout duration must be a positive number.");
        }
        if (typeof cb !== 'function') {
            console.log('error', "Callback is not a function: " + cb);
            throw new Error("Callback must be a function.");
        }
        var lastActivity = Date.now();
        console.log('debug', "Last activity recorded at: " + lastActivity + " milliseconds since epoch.");
        document.addEventListener('mousemove', () => {
            lastActivity = Date.now();
            console.log('debug', "Mouse moved, resetting last activity to: " + lastActivity + " milliseconds since epoch.");
        }
        );
        document.addEventListener('keydown', () => {
            lastActivity = Date.now();
            console.log('debug', "Key pressed, resetting last activity to: " + lastActivity + " milliseconds since epoch.");
        }
        );
        setInterval(() => {
            var currentTime = Date.now();
            console.log('debug', "Current time: " + currentTime + " milliseconds since epoch.");
            if (currentTime - lastActivity >= ms) {
                console.log('debug', "Inactivity detected, executing callback.");
                cb();
            } else {
                console.log('debug', "No inactivity detected, last activity was at: " + lastActivity + " milliseconds since epoch.");
            }
        }
        , ms);
        
        console.log('debug', "Inactivity timeout setup complete.");
    }
}

To Use

let main = new main();
main.OnInactive(30000, () => {
    console.log('debug', "Inactivity detected, locking session.");
    $('.locked-screen').removeClass('d-none');
});

Comments

-3

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

})();

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.