最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to calculate time on a specific screen user spend in react native - Stack Overflow

programmeradmin1浏览0评论

I'm trying to calculate time when user open a specific screen,When he enters in the screen the the time starts and when I exit from the screen the time stops and gives the time spend on the screen

here is my code:

ponentDidMount = () => {
    
    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    this.setState({
      startHour: hours,
      startMin: minutes,
      startSeconds: seconds,
    });
}

Here is ComponentWillunmount

ponentWillUnmount() {

let date = new Date();
let endHours = date.getHours();
let endMinutes = date.getMinutes();
let endSeconds = date.getSeconds();
console.log(`${endHours}:${endMinutes}:${endSeconds}`);
console.log(
  `${this.state.startHour}:${this.state.startMin}:${this.state.startSeconds}`,
);

}

I'm trying to calculate time when user open a specific screen,When he enters in the screen the the time starts and when I exit from the screen the time stops and gives the time spend on the screen

here is my code:

ponentDidMount = () => {
    
    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    this.setState({
      startHour: hours,
      startMin: minutes,
      startSeconds: seconds,
    });
}

Here is ComponentWillunmount

ponentWillUnmount() {

let date = new Date();
let endHours = date.getHours();
let endMinutes = date.getMinutes();
let endSeconds = date.getSeconds();
console.log(`${endHours}:${endMinutes}:${endSeconds}`);
console.log(
  `${this.state.startHour}:${this.state.startMin}:${this.state.startSeconds}`,
);

}

Share Improve this question edited Aug 26, 2020 at 6:01 Zaid Qureshi asked Aug 26, 2020 at 5:26 Zaid QureshiZaid Qureshi 1751 gold badge3 silver badges16 bronze badges 6
  • 2 So what have you tried and where are you having problems? You have only told us your objective but haven't provided any code attempts to solve your issue or any of the research you have done – charlietfl Commented Aug 26, 2020 at 5:38
  • I've added the code you can check it – Zaid Qureshi Commented Aug 26, 2020 at 6:01
  • Ok that's part of it....you still haven't explained where you are having problems – charlietfl Commented Aug 26, 2020 at 6:06
  • i want to calculate difference between the start time and end time,I don't know how to do that – Zaid Qureshi Commented Aug 26, 2020 at 6:07
  • 2 Simplest is just store Date.now() in mount and then subtract that from Date.now() in unmount.... difference will be in ms...do the math to get into whatever format you want it in – charlietfl Commented Aug 26, 2020 at 6:08
 |  Show 1 more ment

3 Answers 3

Reset to default 2

When he enters in the screen the the time starts and when I exit from the screen the time stops and gives the time spend on the screen

It's a very important Feature Request by many for web 2.0 applications. So, I write a detailed, working and simple solution on the subject here.

You are requesting a feature already created for this workflow. It's a plugin you can include in any website. It's none other than time-on-site tracking in timeonsite.js

Look at the following code (Use latest version; don't just copy/paste),

<head>
<script type="text/javascript" src="https://cdnjs.cloudflare./ajax/libs/timeonsite/1.2.0/timeonsitetracker.js"></script>

<script>
var config = {
    // track page by seconds. Default tracking is by milliseconds
    trackBy: 'seconds',

    trackHistoryChange: true, //Single-page React/Angular app

    callback: function(data) { /* callback denotes your data tracking is real-time */
        console.log(data);
        var endPointUrl = 'http://example.' //Replace with your actual backend API URL http://localhost/tos
        if (data && data.trackingType) {
            if (data.trackingType == 'tos') {
                if (Tos.verifyData(data) != 'valid') {
                    console.log('Data abolished!');
                    return; 
                }
            }

            // make use of sendBeacon if this API is supported by your browser.
            if (navigator && typeof navigator.sendBeacon === 'function') {
                data.trasferredWith = 'sendBeacon';
                var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
                navigator.sendBeacon(endPointUrl, blob);
            }
        }
    }
};
var Tos;
if (TimeOnSiteTracker) {
    Tos = new TimeOnSiteTracker(config);
}
</script>

</head>

Then, when you refresh, reload or navigate the React app page,

You'll see following object directly saved into your table/printed in browser console. Select "persist" in logs,

{
    TOSId: 1129620185532,
    TOSSessionKey: "14802525481391382263",
    TOSUserId: "anonymous",
    title: "Test application - Home page",
    URL: "http://nature-blogs/pages/home.php"
    entryTime: "2021-11-27 13:15:48.663",
    currentTime: "2021-11-27 13:17:31.663",
    timeOnPage: 103,
    timeOnSite: 103,
    timeOnPageTrackedBy: "second",
    timeOnPageByDuration: "0d 00h 01m 43s",
    timeOnSiteByDuration: "0d 00h 01m 43s",
    trackingType: "tos",
}

As you can see, the actions

  • "entryTime" is captured
  • "exitTime" is captured in seconds/milliseconds depending upon configuration
  • "type:time_on_site" is captured
  • "timeOnPage" is captured // individual page time
  • "timeOnSite" is captured // session overall page time

What else you need? Since it's stored in SQL DB table, you can do analysis/reporting queries yourself. The same is the case for NoSQL as well. Timeonsite.js is supporting both RDBMS and NoSql DB types.

On top of it, 1.Minimize tab, 2.Inactive tab and 3.Switch tab's idle time are all puted and ignored automatically by the tracker itself.

The only thing to note in configuration part is,

trackHistoryChange: true

If the page routing depends on Location Hash or also known as single-page app, include this setting. On the other hand if your web application is a normal page like Wikipedia, avoid setting this line. You are done. For showing the real-time stay time on screen, check this SO post. It's using Jquery to show the results. You can customize it for your React app.

This tracker can be plugged-in in any library not only in React app but also Angular, Jquery, MooTools etc. since it's plain vanilla JS library.

Let me know if you need more input on the subject. I can assist you on this.

I'm not a react dev but this is fairly simple and this would be the approach.

ponentDidMount = () => {
   /* On init set the start time
      Also: multiplying new Date() by 1 will return a timestamp
    */
   this.startTime = new Date() * 1;
}

ponentWillUnmount() {
    /* Then on view destroy set the endTime */
    let endTime = new Date() * 1;
    /* Subtract the end time with start time, since endTime has greater value. The result
     is the difference between start and end time in milliseconds.
     */
    let elapsed = endTime - this.startTime;
    /* The result is in milliseconds so:
       elapsed / 1000 -> is seconds
       elapsed / 1000 / 60 -> is minutes
       etc.
     */
);

I agree with @masterpreenz

ponentDidMount = () => {
   this.startTime = new Date() * 1;
}

ponentWillUnmount() {
    let endTime = new Date() * 1;
    let elapsed = endTime - this.startTime;
    $('viewPageStayTime').html('You spent '+elaspsed+ ' duration.'); 
);
发布评论

评论列表(0)

  1. 暂无评论