0

I have a single page which contains several parts. I'm using the following navigation menu jsfiddle I want calculate the time spent by the user to read a part of the page. The idea is to trigger an event when the activated part was changed and set a timer, if the timer is bigger than 5 seconds (for example) the user is reading a section then I send an ajax request to save the time spend for reading the given part.

 TrackUserReading(function () { 
                    var sectionName = $("nav ul#sidebar.nav li.active a").html();
                    url = '/Main/TrackUserReading';
                    data = { sectionName: sectionName, time : Timer };
                    var dataType = "json";
                    if(sectionName)
                         $.post(url, data, $.proxy(function (data, textStatus, jqXHR) {
                    }, this), dataType);

But what if the user stays in the same part and he opens a new tab, in this case the timer is not correct.

My question is what the best way to calculate the time spent by a user with a good accuracy. Thanks in advance.

  • What if the user navigates to a new part of the page, then gets up before reading any of it and walks away for a two hour meeting? You're going to have to decide what level of accuracy is acceptable, and maybe throw away the outliers, because your "new tab" and my "2-hour meeting" scenarios _will_ come up and throw off your timing. – Stephen P Mar 09 '15 at 17:39
  • yea this is my question, how can i manage that, what is the best way to have a good accuracy ? – sypahx jugurtha Mar 09 '15 at 17:44

2 Answers2

0

In chrome and firefox the setTimeout is set to fire once every second while the tab is inactive

To check if the tab is active im borrowing the answer from here:

var interval_id;
$(window).focus(function() {
    if (!interval_id)
        interval_id = setInterval(trackUserReading, 1000);
});

$(window).blur(function() {
    clearInterval(interval_id);
    interval_id = 0;
});

When the tab is focused you can execute your function, when the tab is inactive it removes the interval and stops executing your function.

Community
  • 1
  • 1
jimmy jansen
  • 647
  • 4
  • 12
  • what if the computer has 2 screen ? – sypahx jugurtha Mar 10 '15 at 15:44
  • This checks if the focus is on the window of the site, so if the user has two screens and is not actively browsing the current screen the window should go inactive -> I didnt try it, so if you do please confirm – jimmy jansen Mar 10 '15 at 15:50
  • if the user changes the position of the mouse to the2 nd screen, the focus will be inactivated but he can continues reading in the 1 st screen, that means I get less accuracy. In these kind of issues i think we can not get a 100% exactitude, we have to use an error margin – sypahx jugurtha Mar 11 '15 at 15:04
0

The HTML5 Page Visibility API aims to solve that problem, and is supported pretty much everywhere now.

Christophe Marois
  • 6,471
  • 1
  • 30
  • 32