Web based solutions, tutorials, examples and help. 

  • User Idle State and setIntervals()

 #201  by Nito
 Wed Aug 24, 2011 7:42 am
This will allow you to check a users idle state and act accordingly based on the state. Whether you need to update your database, or log them out this code is easily modified.

We utilized Paul Irish's idletimer script for this.

jQuery:
Code: Select all<script type="text/javascript">
$(document).ready(function(){
   function theTimer() {
      $.ajax({
         type: "POST", url: "insert.php", data: "action=active",
         cache : false,
         success: function(html){
            $("#status").html(html);
         }
      });
   }
   var timeout = 30000; // 30 seconds between calling our PHP script
   var idleout = 120000; // Check idle state every 2 minutes. You may want to change this if you are incorporating a chat system
   statusChk = setInterval(function() { theTimer(); }, timeout);
   $(document).bind("idle.idleTimer", function(){
      clearInterval(statusChk);
      statusChk = null;
      $.ajax({
         type: "POST", url: "insert.php", data: "action=idle",
         cache : false,
         success: function(html){
            $("#status").html(html);
         }
      });
   });
   $(document).bind("active.idleTimer", function(){
      if(statusChk==null){ // Check that we're not trying to set it while it's already running
         statusChk = setInterval(function() { theTimer(); }, timeout);
      }
   });
   $.idleTimer(idleout);
});
</script>


HTML:
Code: Select all<div id="status" style="padding:15px 0 0 20px;"></div>


insert.php:
Code: Select all<?php
if(empty($_POST['action'])) die("Denied"); // Check that the action isn't empty

switch($_POST['action']) {
    case 'active':
        echo 'User is now active.';
    break;
    case 'idle':
        echo 'User is now idle.';
    break;
}
?>