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

后端 未结 6 674
情话喂你
情话喂你 2020-12-15 21:06

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

6条回答
  •  半阙折子戏
    2020-12-15 21:56

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

提交回复
热议问题