我在考試頁面上實現了一個計時器計數。它就像edmodo website一樣。但是當你在edmodo參加考試時,即使你刷新它,計時器仍然在計數。在我的網站上,如果刷新頁面,定時器也會刷新。我想要的就像edmodo,即使你刷新頁面仍然在計數。請參閱我的代碼以供參考。如何讓時間計數器繼續刷新或離開頁面
注: 我使用Laravel5.1/jQuery的
$(document).ready(function() {
// Quiz timer (Start of Quiz)
var quiz_timer = $('.quiz-timer').html();
var exact_time = parseInt($('.timer-value').html() - 1);
var hrs_to_spend = parseInt(exact_time/60);
var mins_to_spend = parseInt(exact_time % 60);
var secs_to_spend = 60;
var timeIsUp = false;
var secs = 0,
mins = 0,
hrs = 0;
var secs_zero, mins_zero, hrs_zero, h_spend_zero, m_spend_zero, s_spend_zero;
var setters = setInterval(function() {
if ($('.quiz-timer').html() != '00:00:01') {
if (secs_to_spend > 0) {
secs_to_spend--;
}
if (secs_to_spend <= 0) {
mins_to_spend--;
secs_to_spend = 59;
}
if (mins_to_spend < 0) {
hrs_to_spend--;
mins_to_spend = 59;
}
} else {
$('.quiz-timer').html('00:00:00')
clearInterval(setters);
$('.answer-quiz > .panel-info').attr('class', 'panel panel-danger');
swal({
title: "Oops!",
text: "Time is up.",
type: "warning"
});
timeIsUp = true;
setTimeout(function() {
$('#submitAttempt').click();
}, 2000);
return false;
}
h_spend_zero = (hrs_to_spend < 10) ? '0' : '';
m_spend_zero = (mins_to_spend < 10) ? '0' : '';
s_spend_zero = (secs_to_spend < 10) ? '0' : '';
$('.quiz-timer').html(h_spend_zero + hrs_to_spend + ':' + m_spend_zero + mins_to_spend + ':' + s_spend_zero + secs_to_spend);
if (!timeIsUp) {
secs++;
if (secs == 60) {
mins++;
secs = 0;
}
if (mins == 60) {
hrs++;
mins = 0;
}
hrs_zero = (hrs < 10) ? '0' : '';
mins_zero = (mins < 10) ? '0' : '';
secs_zero = (secs < 10) ? '0' : '';
$('#timeTaken').val(hrs_zero + hrs + ':' + mins_zero + mins + ':' + secs_zero + secs);
}
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Original Value: <span class="timer-value">110</span><br><br>
Timer: <span class="quiz-timer"></span><br>
Time Spent: <input type="text" name="time_taken" id="timeTaken" value="">
嘗試cookie或localStorage –