Calculate online time with Javascript/jQuery

Asked

Viewed 1,779 times

3

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

  • It is necessary to know the seconds?

  • It is necessary yes friend, I do not know the attribute Date very well, but I suppose that if we do not use seconds it will do the updating of the time every 1 minute right? But let’s say the user refreshes the page before completing 1 minute? Then I would end up wasting all this time that has passed..

1 answer

3


Here is a suggestion:

Use the event domready to record the milliseconds (timestamp) when the page loaded. Then use the event beforeunload to run code exactly before the page close. It is also possible to play with the focusin case you want to know when the page is in Focus, or the user is not viewing 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 opens a new window to show seconds. Unlock pop-ups to see the result. This code is an example. You may want to make an AJAX call to register in the database.

  • guy liked your code, how do I play this value for a database? Time user type? Can you help me

Browser other questions tagged

You are not signed in. Login or sign up in order to post.