Keep track of how much time is spent showing certain elements on the page
Asked Answered
H

6

21

So lets say we have 4 Divs (3 hidden, 1 visible), the user is able to toggle between them through javascript/jQuery.

I want to calculate time spent on each Div, and send an xhr containing that time to server to store it in the database. This xhr will be sent when the user toggle the div view.

How can I do that? Any hints will be greatly appreciated.

Thanks,

Habited answered 14/6, 2011 at 9:48 Comment(0)
S
35

At any point, you can record a a start/lap time in a variable with:

var start = new Date();

When you want to calculate the elapsed time, simply subtract the stored date from a new Date instance:

var elapsed = new Date() - start;

This will give you the elapsed time in milliseconds. Do additional math (division) to calculate seconds, minutes, etc.

Stellastellar answered 14/6, 2011 at 9:51 Comment(0)
F
8

Here you go:

HTML:

<div id="divs">
    <div>First</div>
    <div class="selected">Second</div>
    <div>Third</div>
    <div>Fourth</div>
</div>

<p id="output"></p>

JavaScript:

var divs = $('#divs > div'),
    output = $('#output'),
    tarr = [0, 0, 0, 0],
    delay = 100;

divs.click(function() {
    $(this).addClass('selected').siblings().removeClass('selected');
});

setInterval(function() {
    var idx = divs.filter('.selected').index();
    tarr[idx] = tarr[idx] + delay;
    output.text('Times (in ms): ' + tarr);
}, delay);

Live demo: http://jsfiddle.net/7svZr/2/

I keep the times in milliseconds because integers are cleaner and safer (0.1 + 0.2 != 0.3). Note that you can adjust the "precision" (the delay of the interval function) by setting the delay variable.

Foreshow answered 14/6, 2011 at 10:45 Comment(1)
Hi Sime, I used your proof of concept to birth some functionality for a fancyBox. Thank you - alexldixon.com/clicktimerhelp_refined.htmJacqualinejacquard
A
5

Here is a reusable class, example is included in code:

/*
     Help track time lapse - tells you the time difference between each "check()" and since the "start()"

 */
var TimeCapture = function () {
    var start = new Date().getTime();
    var last = start;
    var now = start;
    this.start = function () {
        start = new Date().getTime();
    };
    this.check = function (message) {
        now = (new Date().getTime());
        console.log(message, 'START:', now - start, 'LAST:', now - last);
        last = now;
    };
};

//Example:
var time = new TimeCapture();
//begin tracking time
time.start();
//...do stuff
time.check('say something here')//look at your console for output
//..do more stuff
time.check('say something else')//look at your console for output
//..do more stuff
time.check('say something else one more time')//look at your console for output
Asmara answered 12/1, 2016 at 20:18 Comment(0)
T
2

I use a really easy function to provide time elapsed in this format: hh/mm/ss

onclick/onfocus/etc..

var start_time = new Date();

on leaving:

var end_time = new Date();

var elapsed_ms = end_time - start_time;
var seconds = Math.round(elapsed_ms / 1000);
var minutes = Math.round(seconds / 60);
var hours = Math.round(minutes / 60);

var sec = TrimSecondsMinutes(seconds);
var min = TrimSecondsMinutes(minutes);

function TrimSecondsMinutes(elapsed) {
    if (elapsed >= 60)
        return TrimSecondsMinutes(elapsed - 60);
    return elapsed;
}
Tract answered 18/9, 2013 at 10:52 Comment(0)
V
2

Javascript console internally has a function called "console.time() and console.timeEnd() to do the same. Simple you can use them

console.time("List API");
setTimeout(()=> {
  console.timeEnd("List API");
},5000);

More details can be found here https://developer.mozilla.org/en-US/docs/Web/API/Console/time

Voyeurism answered 16/11, 2018 at 7:47 Comment(0)
B
0

I created an ES6 class based on @Shawn Dotey's answer.

The check() method does not log a message, but returns the elapsed time.

The method start() is not needed in his example (the constructor already "starts" it). So I replaced it by reset() which makes more sense.

export default class TimeCapture
{
    constructor()
    {
        this.reset();
    }

    reset()
    {
        this.startTime = new Date().getTime();
        this.lastTime = this.startTime;
        this.nowTime = this.startTime;
    }

    check()
    {
        this.nowTime = new Date().getTime();
        const elapsed = this.nowTime - this.lastTime;
        this.lastTime = this.nowTime;

        return elapsed;
    }
}

Use it in your project like this:

import TimeCapture from './time-capture';

const timeCapture = new TimeCapture();

setTimeout(function() {
    console.log( timeCapture.check() + " ms have elapsed" ); //~100 ms have elapsed
    timeCapture.reset();
    setTimeout(function() {
        console.log( timeCapture.check() + " ms have elapsed" ); //~200 ms have elapsed
    }, 200);
}, 100);
Britzka answered 4/7, 2020 at 8:22 Comment(1)
Do you find this loses its accuracy if the tab loses focus? I have had unreliability with setTimeout in previous uses. I even used the setTimeout method on a hybrid mobile app and had wild inaccuracies with long periods of use...Corpus

© 2022 - 2024 — McMap. All rights reserved.