Search code examples
javascriptmysqlcountdown

Countdown timer-php+mysql+js


I am working on online examination. In which the examination duration will fetch by mysql(in minutes). I want to show the countdown time on the top of the page.

currently I am using

http://javascript.internet.com/time-date/countdown-timer.html

but the main problem is .. when every time a new question display ..the page get refresh and ..timer reset again from start.

Please help me where is the main problem?

or any other example if you want to suggest?

Thanks


Solution

  • Before running the test you need to calculate exact test end time on the server side and save it into session:

    <?php
    if (empty($_SESSION['test_will_end_by'])) {
        $_SESSION['test_will_end_by'] = time() + $test_duration_in_seconds;
    }
    ?>
    

    Then, if you provide it to your client-side script from HTML:

    Time left:
    <span class="timer" data-end="<?php 
        echo date(DateTime::RFC1123, $_SESSION['test_will_end_by']); 
    ?>"></span>
    

    Add this code into your jQuery DOM-ready handler to start all timers on a page:

    $('.timer').each(function() {
        var target = new Date($(this).data('end')), update, $this = $(this);
        (update = function () {
            var now = new Date();
            $this.text((new Date(target - now)).toUTCString().split(' ')[4]);
            if (Math.floor((target - now)/1000) == 0) return; // timer stops
            setTimeout(update, 1000);
        })();
    });