Я использовал "Обратный обратный отсчет до нуля с момента времени, установленного на часы и минуты", из http://harshen.github.io/jquery-countdownTimer/ на моем сайте, который делает онлайн-экзамен.
Студент должен сдать экзамен и завершить его в течение определенного периода времени, чтобы сказать через n минут.
1> Через n минут страница должна быть автоматически отправлена.
2> До n минут, если студент закроет браузер или вернется или обновит страницу, тогда появится окно подтверждения
i> если да, то страница должна быть отправлена. Но в течение этой продолжительности обратный отсчет должен продолжаться.
ii> если выходите, то ученик должен продолжить экзамен на оставшуюся часть своего времени.
var time_in_sec = parseInt(hours*3600, 10) + parseInt(minutes*60, 10);
time_in_sec *= 1000;
$(function(){
$('#hm_timer').countdowntimer({
hours : hours,
minutes :minutes,
size : "lg"
});
alert("Don't Click Back or Close window before completion.");//Alert before start exam
});
setTimeout(
function(){
alert("You reached the time limit.");
document.getElementById("appear_exam").submit();///form id
},time_in_sec);
jQuery(window).bind('beforeunload', function(event) {
event.stopPropagation();
event.returnValue = "confirm('Do you really want to exit this exam?')";
return event.returnValue;
});
Пожалуйста, помогите Как проверить, были ли все эти действия (закрыть браузер, обновление страницы или щелчок назад) до n минут, и как я могу продолжить обратный отсчет во время таких действий?
Я использовал php-скрипт, чтобы установить время в сеансе вместо таймера jquery, и моя проблема решена.
В контроллере:
if(!empty($test_assigned)){
$test_detail = $this->Test->findById($test_id);
$total_time = explode(':',$test_detail['Test']['total_time']);
$data_arr = $test_detail['Test'];
$data_arr['htime'] = $total_time[0];
$data_arr['mtime'] = $total_time[1];
$test_detail = array('Test'=>$data_arr);
$this->set('test_detail',$test_detail);
$this->set('list',$this->Question->getQuestionsForTest($test_id));
if($this->Session->read('timer_count') != '') {
// session variable_exists, use that
$targetDate = $this->Session->read('timer_count');
} else {//comes here with 1st page load then for each next refresh goes to if
// No session variable, red from mysql
$hours = $data_arr['htime']; // Enter hours
$minutes = $data_arr['mtime']; // Enter minutes
$seconds = 0; // Enter seconds
//$time_limit = ($hours * 60 * 60) + ($minutes * 60) + $seconds + 1; // Convert total time into seconds
$seconds += 1;
$targetDate = strtotime("$hours hours $minutes minutes $seconds seconds");
$this->Session->write('timer_count' , $targetDate);
$this->Session->write('test_id' , $test_id);
}
$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));
$dateFormat = "g:i a";
$actualDateDisplay = date($dateFormat,$actualDate);
$targetDateDisplay = date($dateFormat,$targetDate);
$this->set('remainingHour',$remainingHour);
$this->set('remainingMinutes',$remainingMinutes);
$this->set('remainingSeconds',$remainingSeconds);
В представлении:
<?php echo $this->html->css("timer/font/timer.css");?>
<script type="text/javascript">
var hours = <?php echo $remainingHour; ?>
var minutes = <?php echo $remainingMinutes; ?>
var seconds = <?php echo $remainingSeconds; ?>
//alert(" "+hours+" hr "+minutes+" min "+seconds+" sec");
function setCountDown (){
seconds--;
if (seconds < 0){
minutes--;
seconds = 59;
}
if (minutes < 0){
hours--;
minutes = 59;
}
if (hours < 0){
hours = 23;
}
var h1 = hours; if(h1 == 0 || h1 < 10){h1 = '0'+h1;}
var m1 = minutes;if(m1 == 0 || m1 < 10){m1 = '0'+m1;}
var s1 = seconds;if(s1 == 0 || s1 < 10){s1 = '0'+s1;}
document.getElementById("htd").innerHTML = h1;
document.getElementById("mtd").innerHTML = m1;
document.getElementById("std").innerHTML = s1;
document.getElementById("time_elasped").value = h1+':'+m1+':'+s1;
SD=window.setTimeout( "setCountDown()", 1000 );
if((s1 == '00' || s1 == '0') && (m1 == '00' || m1 == '0') && (h1 == '00' || h1 == '0')){
seconds = "00"; window.clearTimeout(SD);
alert("You reached the time limit.");
document.getElementById("appear_exam").submit();
//window.location = "result.php"
}
}
$(function(){
setCountDown();
});
</script>
<div style="float:left; margin-left:10px; position:fixed; margin-top:-30px;">
<table class="timer-table">
<tr >
<td class="timer-td">Hrs</td>
<td class="timer-td">Mins</td>
<td class="timer-td">Secs</td>
</tr>
<tr>
<td id="htd" class="timer-td1"><?php echo "$remainingHour";?></td>
<td id="mtd" class="timer-td1"><?php echo "$remainingMinutes";?></td>
<td id="std" class="timer-td1"><?php echo "$remainingSeconds";?></td>
</tr>
</table>
</div>