skip to Main Content

I have a website and I want to have a page in this website that measures the time that I’ve spent on the other pages which means when I am on the shopping segment of my website there is a timer that starts counting and as soon as I get off shopping segment of my website it stops Counting and then I can go to a page that tells me how much time I’ve been on each segment of my website

This is the code I got from chat GPT but it is lagging with the time which means that 2 seconds IRL is one second in the website and it doesn’t actually track the usage of the segments

<!-- tracker.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tracker Page</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        #tracker {
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 20px;
        }
        .page {
            display: flex;
            align-items: center;
            width: 80%;
            margin: 10px;
            padding: 10px;
            background-color: white;
            box-shadow: 0 0 5px rgba(0, 0, 0, 0.1);
        }
        .page span {
            flex-grow: 1;
        }
        .page .time, .page button {
            width: 100px;
            padding: 5px;
        }
        .page .time {
            background-color: #3498db;
            color: white;
            text-align: center;
            margin-right: 10px;
        }
        .page button {
            background-color: #2ecc71;
            color: white;
            border: none;
            cursor: pointer;
            margin-right: 5px;
        }
    </style>
</head>
<body>
    <div id="tracker"></div>
    <button id="shoppingPageButton">Shopping Page</button>
    <button id="aboutPageButton">About Page</button>
    <button id="picturesPageButton">Pictures Page</button>
    <button id="trackerPageButton">Tracker Page</button>
    <script>
        document.addEventListener("DOMContentLoaded", function() {
            const trackerContainer = document.getElementById('tracker');

            // Initialize or load the tracked data from localStorage
            let trackedPages = JSON.parse(localStorage.getItem('trackedPages')) || {};

            // Create an array of tracked pages
            const pages = ['shopping', 'about', 'pictures', 'tracker'];

            function createResetButton(page) {
                const resetButton = document.createElement('button');
                resetButton.textContent = 'Reset';
                resetButton.addEventListener('click', () => resetTimer(page));
                return resetButton;
            }

            function updateTracker() {
                trackerContainer.innerHTML = '';
                pages.forEach(page => {
                    const pageDiv = document.createElement('div');
                    pageDiv.classList.add('page');

                    const nameSpan = document.createElement('span');
                    nameSpan.textContent = page.charAt(0).toUpperCase() + page.slice(1);

                    const resetButton = createResetButton(page);

                    const timeDiv = document.createElement('div');
                    timeDiv.classList.add('time');
                    timeDiv.textContent = formatTime(trackedPages[page] || 0);

                    pageDiv.appendChild(nameSpan);
                    pageDiv.appendChild(resetButton);
                    pageDiv.appendChild(timeDiv);
                    trackerContainer.appendChild(pageDiv);
                });
            }

            function formatTime(seconds) {
                const hours = Math.floor(seconds / 3600);
                const minutes = Math.floor((seconds % 3600) / 60);
                const remainingSeconds = seconds % 60;
                return `${hours}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
            }

            function resetTimer(page) {
                trackedPages[page] = 0;
                updateTracker();
                localStorage.setItem('trackedPages', JSON.stringify(trackedPages));
            }

            function startTimer(page) {
                trackedPages[page] = trackedPages[page] || 0;
                let startTime = new Date().getTime();

                const timerInterval = setInterval(() => {
                    const currentTime = new Date().getTime();
                    const elapsedMilliseconds = currentTime - startTime;
                    const elapsedSeconds = Math.floor(elapsedMilliseconds / 1000);
                    
                    // Adjusting for potential lag
                    if (elapsedSeconds > 0) {
                        trackedPages[page] += elapsedSeconds;
                        updateTracker();
                        startTime = currentTime;
                        localStorage.setItem('trackedPages', JSON.stringify(trackedPages));
                    }
                }, 1000);

                return timerInterval;
            }

            // Event listeners for page changes
            pages.forEach(page => {
                const pageButton = document.getElementById(`${page}PageButton`);
                let pageTimerInterval;

                pageButton.addEventListener('click', () => {
                    if (pageTimerInterval) {
                        clearInterval(pageTimerInterval);
                    }
                    pageTimerInterval = startTimer(page);
                });
            });

            // Initial update
            updateTracker();
        });
    </script>
</body>
</html>


I will not provide home.HTML

<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Website Time Tracker</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 0;
            background-color: #f4f4f4;
        }
        header {
            background-color: #3498db;
            padding: 10px;
            text-align: center;
        }
        header button {
            margin: 5px;
            padding: 8px;
            background-color: white;
            border: 1px solid #3498db;
            color: #3498db;
            cursor: pointer;
        }
    </style>
</head>
<body>
    <header>
        <button onclick="location.href='shopping.html'">Shopping</button>
        <button onclick="location.href='pictures.html'">Pictures</button>
        <button onclick="location.href='about.html'">About</button>
        <button onclick="location.href='tracker.html'">Tracker</button>
    </header>
</body>
</html>

2

Answers


  1. listen to the load and unload event of the page.

    on the load event, store the current datatime and then on the unload event, store the current datetime, then do

    time = datetime_from_unload_event - datetime_from_load_event

    now you will have the amount of time you were on the page for.

    which you can then send to the database via an api or store it in a cookie or localStotage.

    Resources

    Login or Signup to reply.
  2. This is much simpler than what you are doing.

    All you need to do is start a timer when the page is done loading and stop the timer when the page is unloaded. The elapsed time can then be stored in localStorage for retrieval when needed.

    The following code won’t work here at Stack Overflow due to sandboxing, but if you try it, you’ll see it works.

    let startTime = null;
    let stopTime = null;
    
    addEventListener("load", function(){
      startTime = new Date();
    });
    
    addEventListener("beforeUnload", function(){
      stopTime = new Date();
    
      // Store the elapsed time in localStorage
      localStorage.setItem("pageCategory", stopTime-startTime);
    });
    
    // Then, on the page where you want to retrieve the times, 
    // you would (uncomment and) add this:
    // let timeAtPageCategory = localStorage.getItem("pageCategory");
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search