我正在编写一个在线定时考试,为了让计时器运行,我正在使用 JS!定时器到时启动并计算时间并提交考试的代码如下:
<script>
//Once the complete page is loaded the GIF image disappears and questions are displayed
function StartTimer()
{
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
}
//Sets the Interval to the time
var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
function submitForm()
{
document.getElementById("submit").submit();
}
function calculate_time()
{
var end_time = "<?php echo $_SESSION["start_time"]; ?>"; // Get end time from session variable (total time in seconds).
var dt = new Date(); // Create date object.
var time_stamp = dt.getTime()/1000; // Get current minutes (converted to seconds).
var total_time = end_time - Math.round(time_stamp); // Subtract current seconds from total seconds to get seconds remaining.
var mins = Math.floor(total_time / 60); // Extract minutes from seconds remaining.
var secs = total_time - (mins * 60); // Extract remainder seconds if any.
if(secs < 10){secs = "0" + secs;} // Check if seconds are less than 10 and add a 0 in front.
document.getElementById("txt").value = mins + ":" + secs; // Display remaining minutes and seconds.
// Check for end of time, stop clock and display message.
if(mins <= 0)
{
if(secs <= 0 || mins < 0)
{
clearInterval(ct);
document.getElementById("txt").value = "0:00";
submitForm();
}
}
}
上面的代码运行良好,即使计时器到期,考试也会自动提交。但是,我试图在主体完全加载后调用 setTimeOut() 和 setInterval() 方法,即setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
应该在 startTimer() 中。
<body onload="StartTimer()">
......
<script>
.....
function StartTimer()
{
document.getElementById('Loading').style.display = "none";
document.getElementById('Loaded').style.display = "block";
document.getElementById('1').style.display = "block";
document.getElementById('qustn1').style.backgroundColor="#dd6e23";
var ct = setInterval("calculate_time()",100); // Start clock.
setTimeOut("submitForm()", <?php echo $time_limit; ?>);
}
.....
</script>
但是当我这样做时,我无法准确地执行代码。即使计时器到达 0:00,考试也无法提交,而是负计时器正在运行!请帮我!!