抱歉,我已经多次问过这个问题,但是没有一个问题/答案可以满足我的确切需求。我尝试过编写,Google搜寻甚至Stackoverflow。我的用例是使用JavaScript(使用PHP从数据库中获取)启动计时器,以供学生单击“开始测试”后立即进行测试,时间到了,提交并整理结果,除非学生在时间之前提交。教师以2:30:45的格式(也保存为DB)“ 2:30:45”的形式输入测试的持续时间2小时30分钟45秒。在自动提交之前,我需要将此倒数至“ 0:00:00”。非常感谢。
这是我的第一个答案,我仍然习惯于StackOverflow。如果我做错了,请告诉我!
假设老师的输入时间是limit
。要获取总秒数:
var hours = limit.split(":")[0];
var mins = limit.split(":")[1];
var secs = parseInt(limit.split(":")[2]);
var totalSecs = 3600*hours+60*mins+secs;
现在您有了总秒数,可以在totalSecs之后提交测试:
setTimeout(function(){
document.querySelector("YOUR FORM ID OR CLASS, ETC.").submit();
},totalSecs);
如果您想显示留给学生的时间:
// Suppose you have a <p id="timeLeft"></p> showing the time left
setInterval(function(){
var hours = 0;
var mins = 0;
var secs = 0;
var numSecs = totalSecs; // Temporary variable
// Convert seconds to HH:MM:SS
while(numSecs>3600){// 1 hour = 3600 seconds, so if numSecs>3600, we can 'take out an hour'
hours++;
numSecs -= 3600;
}
while(numSecs>60){// 1 minute = 60 seconds, so if numSecs>60, we can 'take out a minute'
mins++;
numSecs -= 60;
}
// By now, numSecs will be smaller than 60. numSecs is now the # of seconds
secs = numSecs;
totalSecs--; // Decrease by one second
// Update the time
document.getElementById("timeLeft").innerHTML = ""+hours+":"+mins+":"+secs+" left!";
},1000); // Update the time left every second
更新:防止学生随时间摆弄
客户端中的任何东西都可能被弄乱,因此很难阻止聪明的学生到处乱搞。但是,您可以做的是设置一个const
变量。常量cant可以更改,因此这是一个很好的简单防御方法。您可以设置一个固定日期对象,并检查当前时间是在该日期之前还是之后。如果之后,则我们提交表格。将需要一些PHP代码。
示例:
// const deadline = new Date('December 17, 1995 03:24:00');
const deadline = new Date('<?php echo !!A DATE THAT LOOKS LIKE THE ONE ABOVE!! ?>').toJSON();
// Check every second if past deadline
setInterval(function(){
var now = new Date().toJSON();
if(now>deadline){ // If past deadline
document.getElementById("YOUR FORM").submit();
}
},1000);