0

I have a timer that counts the time spent on a page. I am using https://github.com/jasonzissman/TimeMe.js

If the user leaves the computer, or changes tab, the timer stops (in order to calculate properly the time spent). This, sends to the server the duration every 5 seconds as shown below.

   setInterval(function() { 
    var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
   },5000);

My problem is that if the user leaves the computer, or changes tab, my script will continue to ping the server, updating it with the same "timeSpentOnPage" since it stops when you are not active.

I want to stop sending the data to the server if this happen.

What is a possible way to do this? Maybe to compare 2 different timers?

EnexoOnoma
  • 8,454
  • 18
  • 94
  • 179
  • Consider to use a javascript event to simply clearInterval. https://developer.mozilla.org/en-US/docs/Web/Events one of these should fit your needs –  Dec 27 '16 at 13:55
  • This could help. http://stackoverflow.com/questions/1760250/how-to-tell-if-browser-tab-is-active/1760268#1760268 – Mykola Borysyuk Dec 27 '16 at 13:56

2 Answers2

0

You can try

$(window).on("blur unload",function() {
  TimeMe.stopTimer();
}
$(window).on("focus",function() {
  if (TimeMe) TimeMe.startTimer();
}

and before </body>

<script>
if (TimeMe) TimeMe.startTimer();
</script>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
0

var anId;
document.addEventListener("visibilitychange", function(evt) {
  if(document.visibilityState=='hidden'){
       clearInterval(anId);
  }else{
   anId =  setInterval(function() { 
    console.log("Visible");
    var timeSpentOnPage = TimeMe.getTimeOnCurrentPageInSeconds();
   },5000);  
}
});
Ishank
  • 2,860
  • 32
  • 43