sypahx jugurtha sypahx jugurtha - 6 months ago 24
Javascript Question

Time spent in a part of a page

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.

Answer

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.