![](/img/trans.png)
[英]Why does my timer require a second reload in order to display/start again?
[英]Why does my code output once and then again after timer ends?
我不确定为什么测验完成时(在50秒之前)两次,而计时器结束时又两次输出。 这给我的数据库造成了问题,该数据库一直两次输入数据。 我使用了预先编写的jquery-1.9.1.min.js
和watch.js
。 我下面显示的代码是我编写的代码。 计时器设置为50秒。 这是我的问题的一个例子:
Output after: 20 sec Output after:50 sec
Answer: 3 Answer: 3
Wrong: 6 Wrong: 6
Unanswered: 4 Unanswered: 4
Score: 50 Score:50
Answer: 3
Wrong: 6
Unanswered: 4
Score: 50
index.php代码的第一部分是连接到数据库,并从一个测验表中调用所有数据,该测验包括问题(每个答案4个)和一个“下一步”按钮。
//这里是定时器功能的地方
<div id="demo1" class="demo" style="text-align:center;font-size: 25px;">00:00:00</div>
<script src="js/jquery-1.9.1.min.js"></script>
<script src="js/watch.js"></script>
<script>
$(document).ready(function(){
$('#demo1').stopwatch().stopwatch('start');
var steps = $('form').find(".questions");
var count = steps.size();
steps.each(function(i){
hider=i+2;
if (i == 0) {
$("#question_" + hider).hide();
createNextButton(i);
}
else if(count==i+1){
var step=i + 1;
//$("#next"+step).attr('type','submit');
$("#next"+step).on('click',function(){
submit();
});
}
else{
$("#question_" + hider).hide();
createNextButton(i);
}
});
function submit(){
$.ajax({
type: "POST",
url: "ajax.php",
data: $('form').serialize(),
success: function(msg) {
$("#quiz_form,#demo1").addClass("hide");
$('#result').show();
$('#result').append(msg);
}
});
}
function createNextButton(i){
var step = i + 1;
var step1 = i + 2;
$('#next'+step).on('click',function(){
$("#question_" + step).hide();
$("#question_" + step1).show();
});
}
setTimeout(function() {
submit();
}, 50000);
});
</script>
</body>
</html>
下一个文件ajax.php是显示我的结果以及解决问题的位置。
$response=mysql_query("select id,question_name,answer from questions");
$i=1;
$right_answer=0;
$wrong_answer=0;
$unanswered=0;
while($result=mysql_fetch_array($response)){
if($result['answer']==$_POST["$i"]){
$right_answer++;
}else if($_POST["$i"]==5){
$unanswered++;
}
else{
$wrong_answer++;
}
$i++;
}
echo "<div id='answer'>";
echo " Right Answer : <span class='highlight'>". $right_answer."</span><br>";
echo " Wrong Answer : <span class='highlight'>". $wrong_answer."</span><br>";
echo " Unanswered Question : <span class='highlight'>". $unanswered."</span><br>";
$total=$right_answer+$wrong_answer+$unanswered;
$score=($right_answer/$total)*100;
echo " Your Score : <span class='highlight'>". $score."</span> <br>";
echo "</div>";
$taken = 1;
//insert athlete score
$myscore = "INSERT INTO quiz_results (athlete, score, taken) VALUES ('$_SESSION[loginname]' , '$score', '$taken')";
echo "</br>";
$results= mysql_query($myscore,$con);
if($results)
echo "Score inputted";
您两次调用了commit函数:一次是单击某个人的下一个按钮,第二次是50秒后-与用户的任何操作无关。 只需计算一下submit()
调用即可。
由于用户单击了最后一个“下一步”按钮,因此您应在调用submit()
之前取消超时。
调用setTimeout()
返回超时的ID。 您可以使用它来取消超时。
var timeoutId = setTimeout(function() {
submit();
}, 50000);
然后,当用户回答最后一个问题并单击“下一步”按钮时:
clearTimeout(timeoutId);
submit();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.