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

Viewed 27546

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,

6 Answers

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

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);
Related