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.

4
  • 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? Commented Oct 31, 2016 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 Commented Oct 31, 2016 at 14:38
  • Possible duplicate of Set cookie and get cookie with JavaScript Commented Oct 31, 2016 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. Commented Oct 31, 2016 at 14:51

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.