Calculate time online with JavaScript/jQuery

I need to develop code where I don't have access to back-end languages , I need to make a function that calculates the time a user is online on the page and save this time in localStorage, I thought I would use a setInterval every 1 second to update the time he is online. And then update the value in storage, but I do not know how to work with time in Javascript/jQuery. How could I do that?

Author: bfavaretto, 2014-04-05

1 answers

Here is a suggestion:

Use the domready event to log the milliseconds (timestamp) when the page loads. Then use the beforeunload event to run code just before the page closes. You can also play with focusin case you want to know when the page is in focus, or the user is not seeing that page (without focus).

Code:

var aberturaPagina;
$(window).ready(function () {
    aberturaPagina = new Date().getTime();
});
$(window).on('beforeunload', function () {
    var fechoPagina = new Date().getTime();
    var tempoAberto = (fechoPagina - aberturaPagina) / 1000;

    // faxer qualquer coisa antes de fechar

});

Example

In my example a new window opens to show the seconds. Unlock the pop-ups so you can see the result. This code is an example. You might want to make an AJAX call to log into the database.

 3
Author: Sergio, 2014-04-05 06:08:57