1

I want to keep track of how many seconds a user spend on my project website on all of his pages and for doing this I want to use JavaScript session cookies.
This is because I will host it using Github Pages where I have no access to PHP and also because I want to try working with JS cookies (It's the first time I am doing this).
To count the seconds I am using the followings:

var time_spent = 0;
setInterval(function(){
    ++time_spent;
    $('#counter_container span').html(time_spent);
}, 1000);

The above code works where the counter is but as expected is reseting every time I change the page.
I've tried using a js-cookie library (https://github.com/js-cookie/js-cookie) in the following manner:

Cookies.set('time_spent', time_spent);
var counted_time = Cookies.get('time_spent');
console.log(counted_time);

But the counted_time variable is always 'undefined' whatever I've tried.
I would really apreciate any guidance I can get in order to solve this little issue.

MariusNV
  • 310
  • 3
  • 6
  • 17
  • FYI: setTimeout is not a good way to track time. And why it does not work, where do you set the cookie when you update the value? – epascarello Oct 31 '16 at 14:34
  • 3
    I wouldn't use a timer for this. Instead try setting a timestamp when the user enters the page, and then `onbeforeunload` get the duration and add it to the value stored in the cookie – Rory McCrossan Oct 31 '16 at 14:38
  • Possible duplicate of [Set cookie and get cookie with JavaScript](http://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript) – I wrestled a bear once. Oct 31 '16 at 14:42
  • @epascarello I've used setInterval because is one of the few things I know to do by myself for now and thought that it could serve my purpose here. Thank you for clarifing that is not a good way of tracking the time and regarding where I set the cookie, is done before I use setInterval. I apologize for my lack of knowledge. – MariusNV Oct 31 '16 at 14:51

1 Answers1

2

I wouldn't use a timer for this. Instead try setting a timestamp when the user enters the page, and then onbeforeunload get the duration and add it to the value stored in the cookie. Something like this:

var load = new Date();

window.onbeforeunload = function() {
    var leave = new Date();
    var duration = leave.getTime() - load.getTime() / 1000;
    var counted_time = parseFloat(Cookies.get('time_spent')) || 0;
    Cookies.set('time_spent', counted_time + duration);
}

Working example

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • Thank you for the answer and especially for the working example. I was able to do what I had in min with your help and also learn some new things on the way. – MariusNV Oct 31 '16 at 16:02