Search code examples
jquerydelaymousemove

Mouse/Keyboard inactive ? Execute function if active and only execute once in a sec


I'm making a user count script with PHP and jquery and I would like to have a way of telling if the user is inactive.

$.mousemove(function(){
//get php to update time on user
});

but how should I set it so that it wouldn't update every time it moved but once every 1 sec? Like this?

$.mousemove(function(){
//get php to update time on user
$.delay(1000);    
});

then I will also add a key up function with the same thing so that i can also tell if keyboard is active or not.


Solution

  • Hopefully this is self explanatory, and hopefully it works! This notifies the server immediately when the user moves the mouse, assuming the server hasn't been notified in over a second, AND periodically.

    We schedule activityNotification() to run every second (using something like jQuery timer or the setInterval(func, time) function), in order to handle the following timeline as responsively as possible:

    • 0 ms: user moves mouse, server notified immediately
    • 657 ms: user presses key, but too early to notify server of activity
    • 1000 ms: activityNotification() runs as scheduled, sees that we have activity we have not notified the server about, notifies server
    • 2000 ms: activityNotification() runs as scheduled, but nothing to inform server about
    • 2124 ms: user moves mouse, server notified immediately as it's been 1.124 seconds since the server was last notified

    Code:

    //Track the last activity you saw
    var lastActivity = 0;
    
    //Remember the last time you told the server about it
    var lastNotified = 0;
    
    //Determines how frequently we notify the server of activity (in milliseconds)
    var INTERVAL = 1000;
    
    function rememberActivity() {
        lastActivity = new Date().getTime();
    
        activityNotification();
    }
    
    function activityNotification() {
        if(lastActivity > lastNotified + INTERVAL) {
            //Notify the server
            /* ... $.ajax(); ... */
    
            //Remember when we last notified the server
            lastNotified = new Date().getTime();
        }
    }
    
    setInterval('activityNotification()', INTERVAL);
    
    $.mousemove(function() {
        //Remember when we last saw mouse movement
        rememberActivity();
    });
    
    $.keyup(function() {
        //Remember when we last saw keyboard activity
        rememberActivity();
    });
    

    And remember, not all users will have JavaScript enabled, and this will cause serious battery drain on mobile devices.