0

Recently I'm doing project for E-Library and require Countdown Timer for each book that user read.

So For example in my database 'Users' has '100 seconds' Credit time to read the book and the time will only be decreased when they read the book.

So here's my code:

<?php
        require_once('DatabaseManager.php');
        $databaseManager = new DatabaseManager();
        $books = $databaseManager->getAllRows('books');
        while ($book = mysqli_fetch_assoc($books)) {
            $_SESSION['timer1'] = $book['timer'];
        }
        ?>
         <html>
<head>
<title>Countdown</title>

    <script>
    var clicked = false;
    var sec = <?php echo $_SESSION['timer1'];?>;

    function startClock() {
        if (clicked === false) {
            clock = setInterval("stopWatch()", 1000);
            clicked = true;
        }
        else if (clicked === true) {
        }
    }

    function stopWatch() {
        sec--;
        document.getElementById("timer").innerHTML = sec;


    }

    function updateValue() {
        <?php 
        $time_update = $databaseManager->editRow('books', 'book_id', '1', 'timer', $_GET['REMAINING VALUE FROM COUNTDOWN STORED HERE'] );
        ?>
    }
    </script>
</head>
<body>

    <input type="submit" id="start-clock" value="Start" name="submit" onClick="startClock()"/>

    <div id="timer">0</div>
    <input type="submit" id="stop-clock" value="Stop" name="submit" onClick="updateValue()"/>
    </br>

</body>
</html>

So what i want to do is: when user has credit value of 100 seconds and they only read it for 45 seconds the remaining value of 55 seconds will be stored into the database automatically. using 'updateValue()'

And the other thing is i've tried using button onClick and it's working BUT i want this code to be working whenever the user close the browser.

Thank your in advance.

  • Have a look at [this](http://stackoverflow.com/questions/3888902/javascript-detect-browser-close-tab-close-browser). It might help – Rohan Feb 26 '14 at 05:06

1 Answers1

0

You can do the following :

Send a message (AJAX) to your server every 'n' seconds when the user is reading the book. The server would on receiving the message reduces 'n' seconds from the time remaining for that user's book reading time and send back that time.

The webpage on receiving the time left value, will redirect to another page if the value received is zero or negative.

This way you would be able to track the time remaining with a error of max 'n' seconds.

Akshat Singhal
  • 1,801
  • 19
  • 20
  • thank you but i still couldnt figure how to do it.. i have tried many things and most of them dont seem to work for me – user2780977 Feb 26 '14 at 09:08