Count how much time user has spent on current page

If you would like to present an information to your user on how much time did he or she spend on your webpage, then here is a particular example on how to do this the easiest way I found.

Lets start with simple Javascript code:

var startTime = new Date();

function countTimeSpentHere()
{
    var currentTime = new Date();
    var timerDiv = $("#timer");

    var differenceTime = currentTime - startTime - 3600000; //Small, but required fix...
    var differenceDate = new Date(differenceTime);

    timerDiv.html(formatTime(differenceDate, "HH:MM:SS"));
}

window.setInterval(countTimeSpentHere, 1000);

I’m using a jQuery selector $("#timer") here to catch a div, where time passed by will be presented. If you don’t use jQuery on your page, you have to replace this line with:

var timerDiv = document.getElementById("timer");

and then replace:

timerDiv.html(formatTime(differenceDate, "HH:MM:SS"));

with:

timerDiv.innerHTML = formatTime(differenceDate, "HH:MM:SS");

I’m also using here a formatTime() function, which you may find here to format time spent on current page.

If you don’t need nifty time formatting and prefer only a number of seconds passed since user has entered page, you can forget about formatTime() function and use something like this instead:

function countTimeSpentHere()
{
    var currentTime = new Date();
    var timerDiv = $("#timer"); //or document.getElementById("timer");

    var differenceTime = Math.round((currentTime - startTime) / 1000);

    timerDiv.html(differenceTime);
}

That’s all folks!

Leave a Reply