jeudi 13 août 2015

Java Script Calculating and Displaying Idle Time

I'm trying to write with javascript and html how to display the time a user is idle (not moving mouse or pressing keys). While the program can detect mousemovements and key presses, the program for some reason isn't calling the idleTime() method which displays the time in minutes and seconds.

I'm wondering why the method isn't getting called, as if it is called it would display true or false if a button is pressed.

var startIdle = new Date().getTime();
var mouseMoved = false;
var buttonPressed = false;

function idleTime() {
  document.write(buttonPressed);
  if (mouseMoved || buttonPressed) {
  startIdle = new Date().getTime();
  }
  document.getElementById('idle').innerHTML =   calculateMin(startIdle) + " minutes: " + calculateSec(startIdle)   + " seconds";
  var t = setTimeout(function() {
  idleTime()
  }, 500);
}

function calculateSec(startIdle1) {
  var currentIdle = new Date().getTime();
  var timeDiff = Math.abs(currentIdle - startIdle1);
  var idleSec = Math.ceil(timeDiff / (1000));
  return idleSec % 60;
}

function calculateMin(startIdle1) {
  var currentIdle = new Date().getTime();
  var timeDiff = Math.abs(currentIdle - startIdle1);
  var idleMin = Math.ceil(timeDiff / (1000 * 60));
  return idleMin;
}

var timer;

// mousemove code
var stoppedElement = document.getElementById("stopped");

function mouseStopped() { // the actual function that is called
   mouseMoved = false;
   stoppedElement.innerHTML = "Mouse stopped";
}

window.addEventListener("mousemove", function() {
   mouseMoved = true;
   stoppedElement.innerHTML = "Mouse moving";
   clearTimeout(timer);
   timer = setTimeout(mouseStopped, 300);
});

//keypress code
var keysElement = document.getElementById('keyPressed');

window.addEventListener("keyup", function() {
   buttonPressed = false;
   keysElement.innerHTML = "Keys not Pressed";
   clearTimeout(timer);
   timer = setTimeout("keysPressed", 300);
});

window.addEventListener("keydown", function() {
   buttonPressed = true;
   keysElement.innerHTML = "Keys Pressed";
   clearTimeout(timer);
   timer = setTimeout("keyPressed", 300);

});

function checkTime(i) {
   if (i < 10) {
      i = "0" + i
   }; // add zero in front of numbers < 10
   return i;
}

Here is the HTML code:

<body onload="idleTime()">


    <div id="stopped"><br>Mouse stopped</br></div>
    <div id="keyPressed"> Keys not Pressed</div>

    <strong>
      <div id="header"><br>Time Idle:</br>
      </div>
    <div id="idle"></div>


    </strong>
  </body>



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire