I'm coding an online exam and I want to know when users leave the exam page and when they return to it again. I have
if(document.hasFocus()==false){
                $.ajax({
                type: "POST",
                url: 'submission.php',
                data: {status: 'Absent'},
                success: function(data)
               { alert("Hey, you!"); }
              });
              }
PHP puts the status update, Time and User Ip into a DB. But I'd like to log when they return to the exam so I can calculate the length of absence. Best I've come up with is
<script>
    setInterval(checkFocus, 2000); // updates DB and issues alert every 2 seconds
  function checkFocus()
    {
     if(document.hasFocus()){
        $.ajax({
                type: "POST",
                url: 'submission.php',
                data: {status: 'Present'},
                success: function(data)
               { alert("Good luck in the exam!"); }
              });
          }
     if(document.hasFocus()==false){
                $.ajax({
                type: "POST",
                url: 'submission.php',
                data: {status: 'Absent'},
                success: function(data)
               { alert("Hey, you!"); }
              });
              }
    }
</script>       
I will take the alerts out :) but this code updates the DB every 2 seconds even when user is staying on page. I just can't think of the logic/sequencing to ONLY update DB when user leaves page and returns.
 
    