Search code examples
javascriptangulartimer

Im using Angular and I need to time how long someone has been on a page


I have seen a few ways to do it using vanilla JS and jQuery but unfortunately non of them on how to figure this out using Angular.

I am not the most experienced but I am trying my best to get some sort of timer which when the user clicks on a certain page it trigger the counter, then with ngOnDestory when he leaves the page, stop the counter and send it to the backend to store it in the DB.

If anyone can give any advice on the easiest way to do so please let me know. I have read things such as TimeMe.js which is great but not sure how to implement it using Angular. Also seen the Window Event Handlers on https://developer.mozilla.org/en-US/docs/Web/API/WindowEventHandlers/onbeforeunload.

It does NOT matter if the user is inactive or not looking at the page, that could be resolved after, first I need the timer just to get some research going.

Many thanks for you're time.


Solution

  • You can save timestamp using in ngOnInit and ngOnDestroy like

    ngOnInit (){
        this.startTime = Date.now();
    }
    ngOnDestroy (){
        this.endTime = Date.now();
        totalTime = this.endTime - this.startTime;
    }
    

    Then totalTime will be the time you can send to backend