Countdown timer-php+mysql+js

送分小仙女□ 提交于 2019-12-02 18:04:41

问题


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


回答1:


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);
    })();
});



回答2:


Every time you refresh the page, the JavaScript code will run again, so the timer will be reset. To solve this problem, get the content without refreshing the page, that is : Ajax.




回答3:


You can store the current value in a cookie using the form submit or page beforeunload events. Then when a new page loads, get the remaining time and keep counting down. This also allows for some network latency.

Note that the user may be able to access and modify the value of the cookie.




回答4:


Store the question start time in session, when ever page refreshes get the session start time difference from server and display them in web page. The increment part you can do from the client side javascript code without using AJAX.



来源:https://stackoverflow.com/questions/6420455/countdown-timer-phpmysqljs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!