I am creating a timed testing product in PHP. I am facing a problem in keeping the exam time properly. When the exam is started, and as long as I am in the same screen, the timer is working properly. But when I open other screens while the test is on (say for 10 minutes), and after sometime comeback to the test, the timer is showing wrong time and showing as if only 2 minutes of the test time consumed in previous 10 minutes.
Just want to know why this erratic behavior of the timer of the test when I move out of the screen while the test is on and come back after sometime.
Could anyone help me with this?
PHP CODE
<?php
/*Timer Code*/
$dateFormat = "d F Y -- g:i a";
$targetDate = time() + (240*60);//Change the 240 to however many minutes you want to countdown
$actualDate = time();
$secondsDiff = $targetDate - $actualDate;
$remainingDay = floor($secondsDiff/60/60/24);
$remainingHour = floor(($secondsDiff-($remainingDay*60*60*24))/60/60);
$remainingMinutes = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))/60);
$remainingSeconds = floor(($secondsDiff-($remainingDay*60*60*24)-($remainingHour*60*60))-($remainingMinutes*60));
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
?>
JavaScript
/*Timer Code*/
var days = <?php echo $remainingDay; ?>
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
function setCountDown ()
{
seconds--;
if (seconds < 0){
minutes--;
seconds = 59
}
if (minutes < 0){
hours--;
minutes = 59
}
if (hours < 0){
days--;
hours = 23
}
document.getElementById("remain").innerHTML = "Time "+hours+" H : "+minutes+" M : "+seconds+" S";
SD=window.setTimeout( "setCountDown()", 1000 );
if (hours == '0' && minutes == '00' && seconds == '00')
{
seconds = "00"; window.clearTimeout(SD);
timeStatus = 1;
var response = window.alert("Time is up. Press OK to continue."); // change timeout message as required
} } // here is the end of setCountDown
JavaScript will not always process timer ticks when not running in the foreground, so that is why you get slow-downs.
It would be more reliable if you would:
I will not provide the code for the second or third idea, but here is the code adapted to the first idea (which may be enough for your purposes?):
Replace the
240*60
by a PHP generated value.