我正在用 php 和 Javascript 开发一个测验应用程序。当用户点击提交按钮时测验开始(我不控制测验何时开始)。测验应该在特定时间后停止(我决定)。我不想完全依赖客户端计算机来停止时间,因为客户端计算机时间可以更改。测验不应在页面刷新时重新启动。
我知道 setInterval 和基本的 javascript。到目前为止我开发的功能完美无缺,但测验在页面刷新时重新启动。
function formatSecondsAsTime(secs) {
var hours = Math.floor(secs / 3600);
var minutes = Math.floor(secs / 60) - (hours * 60);
var seconds = secs - (hours * 3600) - (minutes * 60);
return hours + ':' + minutes + ':' + seconds;
}
function startTimer(mytime) {
mytime = mytime.split(":");
hrs = mytime[0];
parseInt(hrs, 10);
mins = mytime[1];
parseInt(mins, 10)
secs = mytime[2];
parseInt(secs, 10);
if (hrs > 0 || mins > 0 || secs > 0) {
timerVar = setInterval(function () {
if (secs > 0) //time is less than a minute
{
displayTime(hrs, mins, secs--);
}
else if (secs == 0 && mins > 0) {
displayTime(hrs, mins = mins - 1, secs = secs + 59);
}
else if (secs == 0 && mins == 0 && hrs > 0) {
displayTime(hrs--, mins = mins + 59, secs = secs + 59);
}
else if (secs == 0 && mins == 0 && hrs == 0) {
clearTimeout(timerVar);
displayTime(0, 0, 0);
}
}, 1000);
}
else {
displayTime(0, 0, 0);
}
}
function displayTime(hrs, mins, secs) {
if (secs > 0 || hrs > 0 || mins > 0) {
if ((secs.toString()).length < 2) secs = "0" + secs;
if ((mins.toString()).length < 2) mins = "0" + mins;
if ((hrs.toString()).length < 2) hrs = "0" + hrs;
document.getElementById("quiztime").innerHTML = "Time remaining: " + hrs + ":" + mins + ":" + secs;
}
else {
document.getElementById("quiztime").innerHTML = "Quiz has ended!";
alert("Quiz has ended. Click ok to continue.");
document.forms["answerForm"].submit();
}
}
请建议我最好的方法。
谢谢你。