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